import java.sql.*;
public class MysqlJdbc {
public static void main(String args[]) {
PreparedStatement pstmt=null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Loading Driver succeeds");
} catch (Exception e) {
e.printStackTrace();
}
try {
String url="jdbc:mysql://localhost:3306/new_db";
String user="root";
String password="123456";
Connection con=DriverManager.getConnection(url,user,password);
//Statement statement=con.createStatement();
String sql= "select id,name,password from (user) where name like ? or password like ?";//先占座,在等待来
//int num=statement.executeUpdate(sql);
pstmt=con.prepareStatement(sql);
pstmt.setString(1,"%"+"c"+"%");//前面的int型数字代表,sql语句中?的那一列 。设置sql中?的值,数据库中的下标从0开始
pstmt.setString(2, "%"+"6"+"%");
ResultSet resultSet=pstmt.executeQuery();//执行查询
//System.out.println("&&&");
while(resultSet.next())
{
System.out.println(resultSet.getInt(1)+" "+resultSet.getString(2)+" "+resultSet.getString(3));//放在ResultSet中的查询结果 下标从1开始
}
pstmt.close();
con.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}JDBC 连接数据库 PreparedStatement的使用
最新推荐文章于 2024-08-14 21:42:11 发布
本文提供了一个使用Java通过JDBC连接并查询MySQL数据库的示例代码。该示例演示了如何加载MySQL驱动、建立连接、创建预编译语句以及执行带参数的SQL查询。
1633

被折叠的 条评论
为什么被折叠?



