JDBC程序的一般编写步骤
1、导入数据库驱动包
2、加载驱动
3、获取连接
4、执行SQL命令
5、处理数据
6、关闭资源
JDBC连接数据库方式一
public class ConnectionTest01 {
public static void main(String[] args) throws Exception {
Driver driver = new com.mysql.jdbc.Driver();
Properties prop = new Properties();
prop.setProperties("user","root");
prop.setProperties("password","root");
Connection conn = driver.connect("jdbc:mysql://localhost:3306/DatabaseName",prop);
System.out.println(conn);
}
}
JDBC连接数据库方式二
public class ConnectionTest02 {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManagment.getConnection("jdbc:mysql://localhost:3306/DatabaseName","root","root");
System.out.println(conn);
}
}
JDBC连接数据库方式三
使用配置文件(properties属性文件)的方式
public class ConnectionTest03 {
public static void main(String[] args) throws Exception {
//创建配置文件,将文件创建在src下
//读取属性文件
InputStream is = Connection.class.getClassLoader().getResourceAsStream("name.properties");
Properties prop = new Properties();
prop.load(is);
Class.forName(prop.getProperties("driver"));
String url = prop.getProperties("url");
String user = prop.getProperties("user");
String password = prop.getProperties("password");
Connection conn = DriverManagment.getConnection(url,user,password);
System.out.println(conn);
}
}
properties配置文件
注:在模块下面的src目录下创建name.properties文件
注:使用键值对存储数据,= 号两边不要有空格
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/DatabaseName
user=root
password=root
DatabaseName是数据库名字
第一个root是用户名
第二个root是密码