码迷,mamicode.com
首页 > 数据库 > 详细

jdbc链接

时间:2017-06-22 01:15:36      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:res   out   localhost   cti   word   []   comm   system   manager   

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

标签:res   out   localhost   cti   word   []   comm   system   manager   

原文地址:http://www.cnblogs.com/mk74/p/7062376.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!