话不多说,show you my code
import java.sql.*;
import java.util.ResourceBundle;
public class jdbcTest0 {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
//注册驱动
//也可使用反射机制加载这个类同时执行其中的静态代码块 Class.forName("com.mysql.jdbc.Driver");
Driver driver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driver);
//获取连接
String url = "jdbc:mysql://10.9.49.105:3306/sentiment?useSSL=false";
String user = "root";
connection = DriverManager.getConnection(url,user,"32009188");
System.out.print("数据库链接对象="+connection);
//以上两步在实际项目中通常封装成util类
//获取数据库操作对象
//PreparedStatement ps = c.prepareStatement(sql)
//prepareStatement会先初始化SQL,先把这个SQL提交到数据库中进行预处理,多次使用可提高效率。可解决sql语句的注入问题
//createStatement不会初始化,没有预处理,每次都是从0开始执行SQL。会产生sql语句的注入问题
statement = connection.createStatement();
//执行sql语句
//对createStatement语句的执行
String sql = "select id,username,password from user";
resultSet = statement.executeQuery(sql);
//count = statement.executeUpdate(sql); 执行插入、更新、删除语句,返回执行该语句数据库中改变的数据项数目
//对prepareStatement语句的执行,更新一条语句
// String sql = "update config set key_= ?, value=? where id = ?";
// try(Connection c = DBUtil.getConnection(); PreparedStatement ps = c.prepareStatement(sql);){
// ps.setString(1,config.key);
// ps.setString(2,config.value);
// ps.setInt(3,config.id);
// ps.execute();
// }
//处理查询结果集
while(resultSet.next()){
String id = resultSet.getString(1);
String username = resultSet.getString(2);
String password = resultSet.getString(3);
System.out.println(id+","+username+","+password);
}
}
catch (SQLException e){
e.printStackTrace();
} finally {
//释放资源,严格按照该先后顺序
try{
if(resultSet!=null){
resultSet.close();
}
}catch (SQLException e){
e.printStackTrace();
}
try{
if(statement!=null){
statement.close();
}
}catch (SQLException e){
e.printStackTrace();
}
try{
if(connection!=null){
connection.close();
}
}catch (SQLException e){
e.printStackTrace();
}
}
}
}