连接mysql数据库
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;
}
}
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 null;
}
return conn;
}
public void closeConn(){
try{
if (conn != null) {
conn.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
public class TestDB {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyDB my = new MyDB();
Connection conn = my.getConn();
if (conn != null) {
System.out.println("ok!");
}else {
System.out.println("error!");
}
}
}