首页 > 代码库 > jdbc链接

jdbc链接

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链接