连接数据库前提条件是:
1、加载mysql驱动
2、获取连接
- 加载驱动前需要将mysql的jar包引入项目
Demo:
package JDBC;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class DBUtil {
private static final String URL = "jdbc:mysql://127.0.0.1:3306/test";
private static final String USER = "root";
private static final String PASSWORD = "root";
private static Connection con;
static {
try {
//1、加载驱动
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
//2、获取链接
con = (Connection) DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection GetConnection() {
return con;
}
}