日期:2014-05-20 浏览次数:20843 次
public class MyDB{这是连接数据库的代码,
private Connection conn=null;
private String jdbcUrl="jdbc:mysql://localhost:3360/manger";
private String user="root";
private String password="123456";
public Connection getConn(){
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(jdbcUrl, user,password);
}
catch(Exception e){
e.printStackTrace();
}
return conn;
}
public void closeConn(){
try{
conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
import java.sql.*;
public class TestDB
{
public static void main(String[] args) throws SQLException
{
MyDB my=new MyDB();
if(!my.getConn().isClosed()){
System.out.println("ok!");
}else
System.out.println("error");
}
}
public static Connection connectDatabase(){
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("数据库连接失败");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("数据库连接失败");
}finally{
return conn;
}
}