当前位置: 移动技术网 > IT编程>开发语言>Java > JDBC建立数据库连接的代码

JDBC建立数据库连接的代码

2019年07月19日  | 移动技术网IT编程  | 我要评论

cnxholes,浙江金鹰校讯通,尚硅谷

本文实例为大家分享了jdbc建立数据库连接的具体代码,供大家参考,具体内容如下

import java.sql.drivermanager;
import java.sql.resultset;
import java.sql.sqlexception;
 
import com.mysql.jdbc.connection;
import com.mysql.jdbc.preparedstatement;
 
public class test {
  public static void main(string[] args) {
     
    //声明connection对象
    connection conn = null;
    preparedstatement preparedstatement = null;
    resultset resultset = null;
    //驱动程序名
    string driver = "com.mysql.jdbc.driver";
    //用户名
    string user = "root";
    //密码
    string password = "1234";
    //url
    string url = "jdbc:mysql://localhost:3306/db_person";
     
    try {
      string sql = "select * from student";
      //1.加载驱动
      class.forname(driver);
      //2.获得connect连接
      conn = (connection) drivermanager.getconnection(url, user, password);
      //3.获得preparedstatement
      preparedstatement = (preparedstatement) conn.preparestatement(sql);
      //4.获得结果集
      resultset = preparedstatement.executequery();
       
      while(resultset.next()) {
        int id = resultset.getint(1);
        string name = resultset.getstring(2);
        string sex = resultset.getstring(3);
        int age = resultset.getint(4);
         
        system.out.println(id +" "+ name + " " + sex + " " + age);
      }
       
    } catch (exception e) {
      // todo auto-generated catch block
      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(conn != null) {
        try {
          conn.close();
        } catch (sqlexception e) {
          // todo auto-generated catch block
          e.printstacktrace();
        }
      }
       
    }
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网