一、Statement
public static void main(String[] args) throws ClassNotFoundException, SQLException {//注册驱动Class.forName("com.mysql.jdbc.Driver");//获取连接String url = "jdbc:mysql://localhost:3306/ns_cloud?useSSL=false&useUnicode=true&characterEncoding=utf-8";String user = "root";String password = "123456";Connection connection = DriverManager.getConnection(url, user, password);//定义sqlString sql = "SELECT t.* FROM ns_cloud.ns_client t where id =1 and is_bind=1 limit 2";//获取执行对象StatementStatement statement = connection.createStatement();//这行sqlResultSet resultSet = statement.executeQuery(sql);//处理结果while (resultSet.next()) {int id = resultSet.getInt("id");String name = resultSet.getString("client_name");// 其他列的数据获取System.out.println("ID: " + id + ", Name: " + name);}//释放资源statement.close();connection.close();}
二、PreparedStatement
public static void main(String[] args) throws ClassNotFoundException, SQLException {//注册驱动Class.forName("com.mysql.jdbc.Driver");//获取连接String url = "jdbc:mysql://localhost:3306/ns_cloud?useSSL=false&useUnicode=true&characterEncoding=utf-8";String user = "root";String password = "123456";Connection connection = DriverManager.getConnection(url, user, password);String preId="1";String isBand="1";//定义sqlString sql = "SELECT t.* FROM ns_cloud.ns_client t where id =? and is_bind=? limit 2";//获取执行对象StatementPreparedStatement preparedStatement = connection.prepareStatement(sql);preparedStatement.setString(1,"1");preparedStatement.setString(2,isBand);//这行sqlResultSet resultSet = preparedStatement.executeQuery();//处理结果while (resultSet.next()) {int id = resultSet.getInt("id");String name = resultSet.getString("client_name");// 其他列的数据获取System.out.println("ID: " + id + ", Name: " + name);}//释放资源preparedStatement.close();connection.close();}