首先引入mysql驅動jar包
mysql-connector-java-5.1.27.jar
直接上代碼
public class User {
private String id ;
private String username ;
private String password;
private String subgroup;
public User() {
super();
}
public User(String id, String username, String password, String subgroup) {
super();
this.id = id;
this.username = username;
this.password = password;
this.subgroup = subgroup;
}
}
public class ConnectionTest01 {
public static void main(String[] args) {
//聲明Connection對象
Connection con;
//驅動程序名
String driver = "com.mysql.jdbc.Driver";
//URL指向要訪問的數據庫名mydata
String url = "jdbc:mysql://localhost:3306/a3test";
//MySQL配置時的用戶名
String user = "root";
//MySQL配置時的密碼
String password = "chao0321o";
//遍歷查詢結果集
try {
//加載驅動程序
Class.forName(driver);
//1.getConnection()方法,連接MySQL數據庫!!
con = DriverManager.getConnection(url,user,password);
if(!con.isClosed()){
System.out.println("Succeeded connecting to the Database!");
}
Statement statement = con.createStatement();
//要執行的SQL語句
String sql = "select * from user";
//3.ResultSet類,用來存放獲取的結果集!!
ResultSet rs = statement.executeQuery(sql);
String username = "";
String id = "";
String password1 = "";
while(rs.next()){
//獲取stuname這列數據
id = rs.getString("id");
//獲取stuid這列數據
username = rs.getString("username");
password1 = rs.getString("password");
//輸出結果
System.out.println(id + "\t" + username + "\t" + password1);
}
rs.close();
con.close();
} catch (Exception e) {
}
}
}