eclipse怎样连接mysql数据库
2个回答
展开全部
链接数据库其实很简单具体代码如下:
package db;
import java.sql.*;
public class DB {
private Connection con=null;
private Statement stmt=null;
private ResultSet rs=null;
public DB(){}
public Connection getConnection(){
String url="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8";
String dbuser="root";
String dbpass="sa";
String name="com.mysql.jdbc.Driver";
if(con==null){
try{
Class.forName(name).newInstance();
}catch(Exception e){
System.out.println(e);
}
try{
con=DriverManager.getConnection(url,dbuser,dbpass);
}catch(Exception e){}
}
return con;
}
public ResultSet exeQuery(String sql){
try{
con=getConnection();
if(con==null){
throw new Exception("没有可连接对象");
}
stmt=con.createStatement();
rs=stmt.executeQuery(sql);
}catch(Exception e){}
return rs;
}
public boolean update(String sql){
boolean flag=true;
try{
con=getConnection();
if(con==null) throw new Exception("没有可连接对象");
stmt=con.createStatement();
stmt.executeUpdate(sql);
}catch(Exception e){
flag=false;
System.out.println("异常:"+e);
}
return flag;
}
public void close(){
try{
if(rs!=null)try{rs.close();}catch(Exception e){System.out.println("rs"+e);}
try{stmt.close();}catch(Exception e){System.out.println("stmt"+e);}
try{con.close();}catch(Exception e){System.out.println("con"+e);}
}catch(Exception e){}
}
}
package db;
import java.sql.*;
public class DB {
private Connection con=null;
private Statement stmt=null;
private ResultSet rs=null;
public DB(){}
public Connection getConnection(){
String url="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8";
String dbuser="root";
String dbpass="sa";
String name="com.mysql.jdbc.Driver";
if(con==null){
try{
Class.forName(name).newInstance();
}catch(Exception e){
System.out.println(e);
}
try{
con=DriverManager.getConnection(url,dbuser,dbpass);
}catch(Exception e){}
}
return con;
}
public ResultSet exeQuery(String sql){
try{
con=getConnection();
if(con==null){
throw new Exception("没有可连接对象");
}
stmt=con.createStatement();
rs=stmt.executeQuery(sql);
}catch(Exception e){}
return rs;
}
public boolean update(String sql){
boolean flag=true;
try{
con=getConnection();
if(con==null) throw new Exception("没有可连接对象");
stmt=con.createStatement();
stmt.executeUpdate(sql);
}catch(Exception e){
flag=false;
System.out.println("异常:"+e);
}
return flag;
}
public void close(){
try{
if(rs!=null)try{rs.close();}catch(Exception e){System.out.println("rs"+e);}
try{stmt.close();}catch(Exception e){System.out.println("stmt"+e);}
try{con.close();}catch(Exception e){System.out.println("con"+e);}
}catch(Exception e){}
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询