import java.sql.*;
public class MySQLDemo {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
public void getConnect(){
// MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL = "jdbc:mysql://localhost:3306/test_database";
String USER = "root";
String PASS = "root";
try{
Class.forName(JDBC_DRIVER);
System.out.println("连接数据库");
this.conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println(" 实例化Statement对象...");
this.stmt = this.conn.createStatement();
}catch (Exception e){
e.printStackTrace();
}
}
public void closeConnect(){
try{
if(this.stmt!=null) this.stmt.close();
}catch(SQLException se2){
}// 什么都不做
try{
if(this.conn!=null) this.conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
public static void main(String[] args) {
MySQLDemo mySQLDemo = new MySQLDemo();
mySQLDemo.getConnect();
try{
mySQLDemo.rs = mySQLDemo.stmt.executeQuery("select * from t_user");
while(mySQLDemo.rs.next()){
// 通过字段检索
int id = mySQLDemo.rs.getInt("id");
String name = mySQLDemo.rs.getString("id");
String url = mySQLDemo.rs.getString("password");
// 输出数据
System.out.print("ID: " + id);
System.out.print(", 站点名称: " + name);
System.out.print(", 站点 URL: " + url);
System.out.print("\n");
}
mySQLDemo.rs.close();
mySQLDemo.stmt.close();
mySQLDemo.conn.close();
}catch (Exception e){
e.printStackTrace();
} finally {
// 完成后关闭
mySQLDemo.closeConnect();
}
}
}
java连接mysql
最新推荐文章于 2023-05-23 14:30:41 发布