首页 > 技术文章 > jdbc

mywangpingan 2018-05-18 16:45 原文

package mybatis.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JdbcTest {

public static void main(String[] args) {
// 数据库连接
Connection connection=null;
// 预编译的Statement,使用Statement提高数据库性能
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
// String url="";
try {
// 加载数据库驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 通过驱动管理类获取数据库连接
connection =DriverManager.getConnection("jdbc:mysql://localhost:3306/project?user=root&password=root&serverTimezone=GMT");
// 定义sql语句
String sql="SELECT * FROM t_user WHERE 1=1 and USER_NAME=?";
// 预处理Statement
preparedStatement=connection.prepareStatement(sql);
// 设置参数,第一个参数为sql语句中的序号(从1开始),第二个参数为设置的参数值
preparedStatement.setString(1, "李四");
// 像数据库发出sql查询
resultSet=preparedStatement.executeQuery();
// 遍历查询结果集
while (resultSet.next()) {
System.out.println(resultSet.getString("USER_ID")+""+resultSet.getString("USER_NAME"));

}

} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

if(preparedStatement!=null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

if(connection!=null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}

}

mysql数据库驱动包8.0.7

推荐阅读