jdbc
package com.demo.advisor.common.entity;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
public class JDBC {
public static void main(String[] args) {
// 使用资源绑定器绑定属性配置文件
ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
String driver = bundle.getString("driver");
String url = bundle.getString("url");
String user = bundle.getString("user");
String password = bundle.getString("password");
Statement statement = null;
Connection conn = null;
try {
// 1、注册驱动
/*driver = new com.mysql.cj.jdbc.Driver();
DriverManager.registerDriver(driver);*/
Class.forName(driver);
// 2、获取连接
conn = DriverManager.getConnection(url, user, password);
System.out.println("数据库连接对象 = " + conn);
// 3、获取数据库操作对象
statement = conn.createStatement();
// 4、执行sql
String sql = "insert into user(username,age,profession,sex) values('王六',21,'学生','男')";
// 专门执行DML语句的(insert delete update)
// 返回值是“影响数据库中的记录条数”
int count = statement.executeUpdate(sql);
System.out.println(count == 1 ? "保存成功" : "保存失败");
// 5、处理查询结果集
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
// 6、释放资源
// 为了保证资源一定释放,在finally语句块中关闭资源
// 并且要遵循从小到大依次关闭
// 分别对其try..catch
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
package com.demo.advisor.common.entity;
import java.sql.*;
import java.util.ResourceBundle;
public class JDBC2 {
public static void main(String[] args) {
// 使用资源绑定器绑定属性配置文件
ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
String driver = bundle.getString("driver");
String url = bundle.getString("url");
String user = bundle.getString("user");
String password = bundle.getString("password");
Statement statement = null;
Connection conn = null;
ResultSet rs = null;
try {
// 1、注册驱动
/*driver = new com.mysql.cj.jdbc.Driver();
DriverManager.registerDriver(driver);*/
Class.forName(driver);
// 2、获取连接
conn = DriverManager.getConnection(url, user, password);
// System.out.println("数据库连接对象 = " + conn);
// 3、获取数据库操作对象
statement = conn.createStatement();
// 4、执行sql
String sql = "select username from user";
// 专门执行DML语句的(insert delete update)
// 返回值是“影响数据库中的记录条数”
rs = statement.executeQuery(sql);
// 5、处理查询结果集
while (rs.next()) {
System.out.println(rs.getString("username"));
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
// 6、释放资源
// 为了保证资源一定释放,在finally语句块中关闭资源
// 并且要遵循从小到大依次关闭
// 分别对其try..catch
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
jdbc.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/sms
user=root
password=123456