JDBC删除与查询
文章目录
- 删除操作
- 查询操作
删除操作
属性配置文件设置
package com.yanyu;
import java.sql.*;
import java.util.ResourceBundle;
public class DelTest {
public static void main(String[] args) {
ResourceBundle bundle = ResourceBundle.getBundle("reswource\\db");
String driver = bundle.getString("driver");
String password = bundle.getString("password");
String user = bundle.getString("user");
String url = bundle.getString("url");
// System.out.println(url);
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
Class.forName(driver);
// 获取连接对象
connection = DriverManager.getConnection(url,user,password);
String sql = "delete from user where name = '烟雨3'";
// 操作对象
statement = connection.createStatement();
statement.execute(sql);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
查询操作
package com.yanyu;
import java.sql.*;
import java.util.ResourceBundle;
public class QueryTest {
public static void main(String[] args) {
ResourceBundle bundle = ResourceBundle.getBundle("resource\\db");
String driver = bundle.getString("driver");
String url = bundle.getString("url");
String user = bundle.getString("user");
String password = bundle.getString("password");
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url,user,password);
String sql = "select * from user";
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
while (resultSet.next()){
String name = resultSet.getString("name");
// 与数据库字段名字一致
String password1 = resultSet.getString("password");
System.out.print("姓名:" + name);
System.out.print("\t\t\t");
System.out.println("密码:" + password1);
}
resultSet.toString();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}