
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){}
}
一、 安装RODBC库1、进入R语言的GUI界面(RGUI.EXE),在菜单栏选择“程序包/安装程序包
2、在d出的窗口里往下拉,选择RODBC如图,点击确定
3、在ODBC数据源管理器里将需要的数据库添加进去,这里笔者使用的是SQL Server2008,驱动程序选择Native Client10.0
3、在R语言窗口输入连接语句
>library(RODBC)
**这里是载入RODBC库
>channel<-odbcConnect("MyTest",uid="ripley",case="tolower")
**连接刚才添加进数据源的“MyTest”数据库
**ch <- odbcConnect("some dsn ", uid = "user ", pwd = "**** ")
**表示用户名为user,密码是****,如果没有设置,可以直接忽略
>data(USArrests)
**将“USArrests”表写进数据库里(这个表是R自带的)
>sqlSave(channel,USArrests,rownames = "state",addPK = TRUE)
**将数据流保存,这时候打开SQL Server就可以看到新建的USArrests表了
>rm(USArrests)
>sqlTables(channel)
**给出数据库中的表
>sqlFetch(channel,"USArrests",rownames = "state")
**输出USArrests表中的内容
>sqlQuery(channel,"select * from USArrests")
**调用SELECT查询语句并返回结果(如图)
>sqlDrop(channel,"USArrests")
**删除表
>odbcClose(channel)
**最后要记得关闭连接
当然,通过这个办法也可以读取Excel、Access表中的内容,具体方法类似,这里不再重复
(1)连接MySQL数据库首先要下载加载RMySQL这个包。
加载的时候可以使用
[plain] view plain copy
require(RMySQL)
或者
[plain] view plain copy
library(RMySQL)
这两个语句的功能是一样的。
现在是建立连接:
[plain] view plain copy
con<-dbConnect(MySQL(),host='localhost',port=3306,dbname="XXX",user="root",password="XXXXX")
这里连接的是本地数据库,host=‘localhost’,也可以写成host='127.0.0.1',port为端口,如果不知道的话可以在mysql控制台输入 status来查看数据库的当前配置。其中就包括端口。user为用户名,一般为root,password是你的数据库的密码。
若数据库中的信息是中文,我们就要修改此连接的编码,否则就会出现乱码。
[plain] view plain copy
dbSendQuery(con,"set character_set_result=gbk")
dbSendQuery(con,"set character_set_connection=gbk")
dbSendQuery(con,"set character_set_database=gbk")
dbSendQuery(con,"set character_set_client=gbk")
这样就搞定了,R已经连接到我们自己的MySQL数据库了。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)