今天我们来看看如何通过java代码连接mysql数据库,
有三种方式,先导入mysql的驱动程序包,
package demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import com.mysql.jdbc.Driver;
public class Sql1 {
private static String url="jdbc:mysql://localhost:3306/shuying";
private static String user="root";
private static String password="root";
public static void main(String[] args) throws Exception {
//t1();
//t3();
t2();
}
//使用驱动管理类
private static void t2() throws SQLException {
//注册一次驱动
Driver driver=new com.mysql.jdbc.Driver();
//注册驱动
DriverManager.registerDriver(driver);
.使用驱动管理类获取连接
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
//改良版,只用注册一次
private static void t3() throws ClassNotFoundException, SQLException {
//1、通过反射获取对象(只需注册一次)
Class.forName("com.mysql.jdbc.Driver");
//2.使用驱动管理类获取连接
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
//直接使用驱动程序连接
private static void t1() throws SQLException {
//创建驱动实现类对象
Driver driver=new com.mysql.jdbc.Driver();
Properties properties=new Properties();
properties.setProperty("user", user);
properties.setProperty("password", password);
//连接数据库
Connection connect = driver.connect(url, properties);
System.out.println(connect);
}
}