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-03-15 13:57:37 发布