1. 程式人生 > >jdbc鏈接

jdbc鏈接

nts row java for pack 默認 trace port except

package wmk;

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

public class JbcdTestAll2 {

//static final 變量應該用大寫
// Class.forName("oracle.jdbc.driver.OracleDriver");
//NAME = "jdbc:oracle:" + "thin:@127.0.0.1:1521:XE";// 127.0.0.1是本機地址,XE是精簡版Oracle的默認數據庫名

public static final String URL = "jdbc:mysql://localhost:3306/community";
public static final String NAME = "com.mysql.jdbc.Driver";
public static final String USER = "wmk";
public static final String PASSWORD = "admin";

Connection conn = null;
PreparedStatement statement = null;
ResultSet res = null;
String a = "";
String b = "";
String c = "";

public JbcdTestAll2(String sql) throws SQLException {
try {
  //註冊驅動
  Class.forName(NAME);
  //獲取鏈接
  conn = DriverManager.getConnection(URL, USER, PASSWORD);
  //創建查詢
  statement = conn.prepareStatement(sql);
  //使用resultset獲取查詢結果 executeUpdate(sql) 返回影響行數,用於插入 修改 刪除
  res = statement.executeQuery();
  //遍歷結果集
  while (res.next()) {
  a = res.getString(1);
  b = res.getString(2);
  c = res.getString(3);
  System.out.println(a+" - "+b+" - "+c);
  }
  //調用關閉方法,釋放資源
  close();
  } catch (ClassNotFoundException e) {

     e.printStackTrace();
   }
 }
//封裝關閉為一個方法
public void close(){
  try {
    if (conn!=null) {
    conn.close();
  }
  if (statement!=null) {
    statement.close();
  }
  if (res!=null) {
    res.close();
  }
  } catch (Exception e) {
    e.printStackTrace();
  }
}

  public static void main(String[] args) throws SQLException {
    JbcdTestAll2 a = new JbcdTestAll2("select * from news");

  }
}

jdbc鏈接