1. 程式人生 > >JDBC java對MySQL資料庫進行查詢操作,並把查詢的結果輸出

JDBC java對MySQL資料庫進行查詢操作,並把查詢的結果輸出

Resultset中的所有資料都可以通過getString()方法取得

String是可以接收表中的任意型別列的內容,所以在以下的程式中全部都使用getString()接收

package JDBC;
import java.sql.*;
public class MySQLquery {
public static final String DRIVER = "com.mysql.jdbc.Driver"; 
public static final String URL = "jdbc:mysql://127.0.0.1:3306/lianxi";   
public static final String USERNAME = "root";  
public static final String PASSWORD = "123456";
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Connection conn = null; //每一個Connection物件表示一個數據庫連線物件
Statement stat = null;
Class.forName(DRIVER);//載入驅動程式
conn=DriverManager.getConnection(URL,USERNAME,PASSWORD);
stat = conn.createStatement();//找到藉口
String sql = "select*from hehe";//查詢語句
ResultSet rs=stat.executeQuery(sql);//查詢
//將查詢出的結果輸出
while (rs.next()) {
String deptno=rs.getString("deptno");
String dname=rs.getString("dname");
String loc=rs.getString("loc");

下列三行語句與上面三行語句作用相同,僅需一個就行

String deptno=rs.getString(1);
String dname=rs.getString(2);
String loc=rs.getString(3);

System.out.println("deptno:"+deptno+",dname:"+dname+",loc:"+loc);
}
rs.close();
stat.close();
conn.close();
}
}