JDBC建立数据库连接的代码
程序员文章站
2024-04-01 20:27:10
本文实例为大家分享了jdbc建立数据库连接的具体代码,供大家参考,具体内容如下
import java.sql.drivermanager;
import...
本文实例为大家分享了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(); } } } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: Java this 关键字的使用方法详解
下一篇: PHP 根据key 给二维数组分组