数据库连接的代码
数据库连接前的准备
数据库连接的jar包
数据库连接的java代码:
package com.it.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Dbutil {
private String jdbcName="com.mysql.jdbc.Driver";
private String dbUserName="root";
private String dbpassword="123456";
private String dbUrl="jdbc:mysql://localhost:3306/db_studentInfo";
/*
* 获取数据库连接
*/
public Connection getCon()throws Exception{
Class.forName(jdbcName);
System.out.println("驱动包加载成功");
Connection con=DriverManager.getConnection(dbUrl, dbUserName, dbpassword);
return con;
}
/**
* 关闭数据库
* @param con Connection
* @throws Exception
*/
public void closeCon(Connection con) throws Exception{
if(con!=null){
con.close();
}
}
public static void main(String[] args) throws Exception {
Dbutil dbUtil=new Dbutil();
Connection con=null;
try {
con=dbUtil.getCon();
System.out.println("数据库连接成功");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
dbUtil.closeCon(con);
}
}
}