shenzhang 发表于 2018-10-21 13:36:43

JDBC系列:(2)使用Statement执行sql语句

package com.rk.db.b_statement;  

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

  
/**
  
* 使用Statement执行DQL语句(查询操作)
  
* @author RK
  
*
  
*/
  
public class Demo03
  
{
  static
  {
  try
  {
  //1.驱动注册程序
  Class.forName("com.mysql.jdbc.Driver");
  }
  catch (ClassNotFoundException e)
  {
  throw new RuntimeException(e);
  }
  }
  public static void main(String[] args)
  {
  Connection conn = null;
  Statement stmt = null;
  ResultSet rs = null;
  String url = "jdbc:mysql://localhost:3306/testdb";
  String user = "root";
  String password = "root";
  try
  {
  //2.获取连接对象
  conn = DriverManager.getConnection(url, user, password);
  //3.创建Statement
  stmt = conn.createStatement();
  //4.准备sql
  String sql = "SELECT * FROM T_Persons";
  //5.发送sql语句,执行sql语句,得到返回结果
  rs = stmt.executeQuery(sql);
  //6.输出
  while(rs.next())
  {
  int id = rs.getInt("Id");
  String userName = rs.getString("UserName");
  String pwd = rs.getString("Pwd");
  System.out.println(id + "\t" + userName + "\t" + pwd);
  }
  }
  catch (SQLException e)
  {
  e.printStackTrace();
  }
  finally
  {
  closeQuietly(rs);
  closeQuietly(stmt);
  closeQuietly(conn);
  }
  }
  

  /**
  * 安静的关闭
  */
  private static void closeQuietly(AutoCloseable ac)
  {
  if(ac != null)
  {
  try
  {
  ac.close();
  }
  catch (Exception e)
  {
  e.printStackTrace();
  }
  }
  }
  
}


页: [1]
查看完整版本: JDBC系列:(2)使用Statement执行sql语句