Java通过JDBC连接MySql数据库

时间:2022-10-27 13:04:58
public static Connection get_conn(){
/**
* @author kian
* @description 使用jdbc连接数据库
* @return Connection
*/

Connection conn = null;

// 1、加载数据库驱动(以MySql为例)类
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e){
System.out.println("找不到驱动类,数据库驱动加载失败!");
e.printStackTrace();
}

//2、通过DriverManager连接数据库
/**
* 协议构成
* jdbc: 协议名称
* mysql: 子协议名称
* localhost:3306/test: 数据源标识(地址:端口/数据库名称)
*/
String url = "jdbc:mysql://192.168.2.240:3306/test";
String db_name = "root";
String db_passwd = "moma";
try{
conn = DriverManager.getConnection(url, db_name, db_passwd);
}catch(SQLException e){
System.out.println("数据库连接失败");
e.printStackTrace();
}

return conn;
}