jdbc的簡單使用,jdbc簡單使用

來源:互聯網
上載者:User

jdbc的簡單使用,jdbc簡單使用

1.載入驅動(mysql的驅動是com.mysql.jdbc.Driver,SqlServer的驅動是 com.microsoft.sqlserver.jdbc.SQLServerDriver)

2.載入資料庫的串連(url, username,password)

3.編寫sql語句(String sql="select * from grade  where gradeName = ?";)

4.遍曆查詢結果 【while (resultSet.next()) {
   System.out.println(resultSet.getInt("gradeId") + "  " + resultSet.getString("gradeName"));
  }】

5.關閉資源(從後向前關閉資源 )

 

public class Test {
public static void main(String[] args) {
 Connection connection = null;
 PreparedStatement preparedStatement = null;
 ResultSet resultSet = null;
 try {
  // 載入資料庫驅動
  Class.forName("com.mysql.jdbc.Driver");
  // 通過驅動管理類擷取資料庫連結
  connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myschool?characterEncoding=utf-8", "root", "root");
  // 定義sql語句 ?表示預留位置
  String sql = "select * from grade  where gradeName = ?";
  // 擷取預先處理statement
  preparedStatement = connection.prepareStatement(sql);
  // 設定參數,第一個參數為sql語句中參數的序號(從1開始),第二個參數為設定的參數值
  preparedStatement.setString(1, "二年級");
  // 向資料庫發出sql執行查詢,查詢出結果集
  resultSet = preparedStatement.executeQuery();
  // 遍曆查詢結果集
  while (resultSet.next()) {
   System.out.println(resultSet.getInt("gradeId") + "  " + resultSet.getString("gradeName"));
  }
 } catch (Exception e) {
  e.printStackTrace();
 } finally {
  // 釋放資源
  if (resultSet != null) {
   try {
    resultSet.close();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  if (preparedStatement != null) {
   try {
    preparedStatement.close();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  if (connection != null) {
   try {
    connection.close();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.