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

Python015

如何用R语言连接和管理MYSQL数据库,第1张

链接数据其实很简单具体代码如下:

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){}

}

如何把R语言中的中文数据导入到mysql

一些常用的数据,处理好,放在mySQL里,以后使用起来也方便。

可以用R直接进行分析,具体步骤如下:

1、R下载RODBC包,安装好。

2、在http://dev.mysql.com/downloads/connector/odbc

下载mySQL ODBC,安装好。

3、windows:控制面板->管理工具->数据源(ODBC)->双击->添加->选中mysql ODBC driver一项

填写:data source name 一项填入你要使用的名字,自己随便命名,例如:mysql_data

description一项随意填写,例如mydata

TCP/IP Server 填写本机服务器IP,一般为:127.0.0.1

user 填写你的mysql用户名

password 填写你的mysql密码

然后数据库里会出现你的mysql里的所有数据库,选择一个数据库。

确定。

4、打开R的界面调用数据库:

1 2 3 4

library(RODBC)channel <- odbcConnect("mysql_data", uid="root",pwd="123")sqlTables(channel)#查看数据中的表 data<-sqlFetch(channel,"kegg")# 查看表的内容,存到数据框里