一、添加Mysql驱动和Druid依赖
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
二、编写代码
public class DruidDemo {
public static void main(String[] args) throws Exception {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/dbxx");
dataSource.setUsername("xxxx");
dataSource.setPassword("xxxxxxx");
DruidPooledConnection connection = dataSource.getConnection();
String sql = "select * from user_profile where id=? or id=?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,2);
preparedStatement.setInt(2,3);
ResultSet resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
System.out.print(resultSet.getString(1)+" ");
System.out.print(resultSet.getString(2)+" ");
System.out.print(resultSet.getString(3)+" ");
System.out.print(resultSet.getInt(4)+" ");
System.out.println(resultSet.getInt(5));
}
resultSet.close();
connection.close();
}
}
三、控制台输出