Mysql数据库带参数的搜索语句

package cn.server.dao;

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

public class SqlServerHelper {
        public static void main(String[] args) {
        ResultSet rs = null;
        Connection conn = null;
        PreparedStatement pst = null;
        try {
           //第一步:加载MySQL的JDBC的驱动
              Class.forName("com.mysql.jdbc.Driver");
            //取得连接的 url,能访问MySQL数据库的用户名,密码;数据库名
              String url = "jdbc:mysql://localhost:3306/video";
              String user = "root";
              String password = "root";
            //第二步:创建与MySQL数据库的连接类的实例
              conn = DriverManager.getConnection(url, user, password);
            //第三步:用conn创建Statement对象类实例 stmt

               String sql = "select country_id,country_name from tb_country where country_id=? ";

            //String sql = "select country_id,country_name from tb_country where country_id=? and country_name=? ";

               pst = conn.prepareStatement(sql);   
            //1代表第一个参数,2代表该参数的值
               pst.setInt(1, 1);
            // 2代表第二个参数,日本代表该参数的值
            // pst.setString(2, "日本");
               rs = pst.executeQuery();
               while(rs.next()){
                   System.out.println(rs.getString("country_id"));
                   System.out.println(rs.getString("country_name"));
               }
         }catch (ClassNotFoundException e) {  
                     //加载JDBC错误,所要用的驱动没有找到
                  System.out.println("驱动加载错误");
         } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }

   }

}


    

猜你喜欢

转载自blog.csdn.net/hnwolfs/article/details/50544544