Jdbc:
1.mysql
要引入mysql的驱动
package cn.javaearn.jdbc.mysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class TestConnection {
public static void main(String[] args) {
//真正开发中的连接方式
String url="jdbc:mysql://localhost:3306/oadata";
try {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接
Connection conn=DriverManager.getConnection(url,"root","root");
System.out.println("conn"+conn);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
http://www.javalearns.com/
数据库管理类:
package cn.javaearn.mysql.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 数据库管理类
* @author Administrator
*/
public class DBManager {
private String className="com.mysql.jdbc.Driver";
private String username="root";
private String psw="root";
private String url="jdbc:mysql://localhost:3306/test";
/**
* 注册驱动
*/
public DBManager(){
try {
Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
http://www.javalearns.com/
/**
* 获取连接
*/
public Connection getConnection(){
Connection conn=null;
try {
conn=DriverManager.getConnection(url,username,psw);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 关闭资源
*/
public void closeResource(Connection conn,Statement stmt,ResultSet rs){
try {
if(rs!=null){
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if(stmt!=null){
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}