如何用R语言连接和管理MYSQL数据库

如题所述

链接数据库其实很简单具体代码如下:
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){}
}
温馨提示:答案为网友推荐,仅供参考
相似回答