JDBC
JDBC(Java Database Connectivity)
Java database connection specification (a set of interfaces) provided by Sun company
JDBC core class
DriverManager create connection
Connection connection class
Statement execute sql statement
ResultSet result set
JDBC connection steps
1. Registration driver
2. Get the connection
3. Get the execution object Statement of sql Statement
4. execute sql statement to return ResultSet
5. Processing result set
6. Close resources
Registration driven
//It should be noted that this registration method is equivalent to two times of registration
//Because the static code block inside the Driver class has been registered once
DriverManager.registerDriver(new Driver));
//Directly load the class into memory. The parameter is the fully qualified class name (package name + class name)
Class.forName("com.mysql.jdbc.Driver");
Get connection object
String url = "jdbc:mysql://localhost:3306/myjdbc";
//Connection mode 1:
Connection connection = DriverManager.getConnection(url, "root", "123456");
//Connection mode 2:
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "123456);
Connection connection = DriverManage.getConnection(url, info);
//Connection mode 3: it is equivalent to using a get request to access the link with parameters
String url = "jdbc:mysql:
Connection connection = DriverManager.getConnection(url);
Statement statement = connection.createStatement();
String sql = "select * from users";
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()) {
System.out.print(resultSet.getObject(1));
System.out.print(resultSet.getObject(2));
System.out.print(resultSet.getObject(3));
System.out.print(resultSet.getObject(4));
System.out.println(resultSet.getObject(5));
}
resultSet.close();
statement.close();
connection.close();
Test addition, deletion, modification and query
@Test
public void testInsert() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/myjdbc?user=root&password=123456";
Connection connection = DriverManager.getConnection(url);
Statement statement = connection.createStatement();
String sql = "insert into users values(4, 'zs', '123', '123@163.com', '2018-01-01
int row = statement.executeUpdate(sql);
System.out.println(row);
if (row > 0) {
System.out.println("Insert success");
}
statement.close();
connection.close();
}
@Test
public void testUpdate() throws Exception {
Class.forName("com.mysql.jdbc.Driver")
String url = "jdbc:mysql://localhost:3306/myjdbc?user=root&password=123456"
Connection connection = DriverManager.getConnection(url)
Statement statement = connection.createStatement()
String sql = "update users set name='zs"
int row = statement.executeUpdate(sql)
System.out.println(row)
if (row > 0) {
System.out.println("Update success")
}
statement.close()
connection.close()
}
@Test
public void testDelete() throws Exception {
Class.forName("com.mysql.jdbc.Driver")
String url = "jdbc:mysql://localhost:3306/myjdbc?user=root&password=123456"
Connection connection = DriverManager.getConnection(url)
Statement statement = connection.createStatement()
String sql = "delete from users where id=5"
int row = statement.executeUpdate(sql)
System.out.println(row)
if (row > 0) {
System.out.println("Delete successful")
}
statement.close()
connection.close()
}
@Test
public void testSelect() throws Exception {
Class.forName("com.mysql.jdbc.Driver")
String url = "jdbc:mysql://localhost:3306/myjdbc?user=root&password=123456"
Connection connection = DriverManager.getConnection(url)
Statement statement = connection.createStatement()
// query
String sql = "select id, name, email from users"
ResultSet resultSet = statement.executeQuery(sql)
// Process result set
while (resultSet.next()) {
// You can directly fill in the field name
System.out.print(resultSet.getObject("id") + " ")
System.out.print(resultSet.getObject("name") + " ")
System.out.println(resultSet.getObject("email") + " ")
}
resultSet.close()
statement.close()
connection.close()
}
Exception handling when connecting to database
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/myjdbc";
connection = DriverManager.getConnection(url, "root", "123456");
statement = connection.createStatement();
String sql = "select * from users";
resultSet = statement.executeQuery(sql);
ArrayList<User> arrayList = new ArrayList<>();
while(resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setPassword(resultSet.getString("password"));
user.setEmail(resultSet.getString("email"));
user.setBirthday(resultSet.getDate("birthday"));
arrayList.add(user);
}
for (User user : arrayList) {
System.out.println(user);
}
} catch (ClassNotFoundException e) {
throw new RuntimeException("Driver load failed");
} catch (SQLException e) {
throw new RuntimeException("Failed to get connection");
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
throw new RuntimeException("Resource shutdown failed");
}
resultSet = null;
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
throw new RuntimeException("Resource shutdown failed");
}
statement = null;
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException("Resource shutdown failed");
}
connection = null;
}
}
}
Create the dbinfo.properties file as the configuration file
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/myjdbc
user=root
password=123456
take JDBC Encapsulation as a tool class method
public class JDBCUtil {
private static String driverClass;
private static String url;
private static String user;
private static String password;
static {
Properties properties = new Properties();
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream("src/dbinfo.properties");
properties.load(fileInputStream);
driverClass = properties.getProperty("driverClass");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
} catch (Exception e) {
e.printStackTrace();
}
ResourceBundle resourceBundle = ResourceBundle.getBundle("dbinfo");
driverClass = resourceBundle.getString("driverClass");
url = resourceBundle.getString("url");
user = resourceBundle.getString("user");
password = resourceBundle.getString("password");
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException, ClassNotFoundException {
return DriverManager.getConnection(url, user, password);
}
public static void closeAll(ResultSet resultSet, Statement statement, Connection connection) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
throw new RuntimeException("Resource shutdown failed");
}
resultSet = null;
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
throw new RuntimeException("Resource shutdown failed");
}
statement = null;
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException("Resource shutdown failed");
}
connection = null;
}
}
}
test JDBC Tool class
public class TestJDBCUtil {
@Test
public void testSelect() {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = JDBCUtil.getConnection();
statement = connection.createStatement();
String sql = "select * from users";
resultSet = statement.executeQuery(sql);
ArrayList<User> arrayList = new ArrayList<>();
while(resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setPassword(resultSet.getString("password"));
user.setEmail(resultSet.getString("email"));
user.setBirthday(resultSet.getDate("birthday"));
arrayList.add(user);
}
for (User user : arrayList) {
System.out.println(user);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtil.closeAll(resultSet, statement, connection);
}
}
}
SQL statement injection problem
public class Login {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your account number:");
String name = scanner.nextLine();
System.out.println("Please input a password:");
String password = scanner.nextLine();
DoLogin doLogin = new DoLogin();
User user = doLogin.findUser(name, password);
if (user != null) {
System.out.println(user);
} else {
System.out.println("Login failed");
}
scanner.close();
}
}
public class DoLogin {
public User findUser(String name, String password) {
String sql = "select * from users where name = '" + name + "' and password = '" + password + "'";
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
User user = null;
try {
connection = JDBCUtil.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
System.out.println(sql);
if (resultSet.next()) {
user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setPassword(resultSet.getString("password"));
user.setEmail(resultSet.getString("email"));
user.setBirthday(resultSet.getDate("birthday"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtil.closeAll(resultSet, statement, connection);
}
return user;
}
}
sql Statement injection problem,Add the condition of permanent establishment
//The result is that the input sql statement is equivalent to select * from users;
Solution
public User findUser(String name, String password) {
String sql = "select * from users where name = ? and password = ?";
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
User user = null;
try {
connection = JDBCUtil.getConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, name);
preparedStatement.setString(2, password);
resultSet = preparedStatement.executeQuery();
System.out.println(sql);
if (resultSet.next()) {
user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setPassword(resultSet.getString("password"));
user.setEmail(resultSet.getString("email"));
user.setBirthday(resultSet.getDate("birthday"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtil.closeAll(resultSet, preparedStatement, connection);
}
return user;
}