Myeclipse连接Mysql!

 刚搞了下Mysql和Myeclipse的连接,为省各位走弯路,特贴此出来供大家参考!

第一步:首先到Mysql官网下载Mysql,安装时要注意的一点就是要选择编码方式,改为gb2312,以防以后的数据存取产生乱码!

第二步:用Mysql命令行建立表,举个例子:

drop database if exists user1;

create user1;

use user1;

CREATE TABLE userinfo( 
        id char(10) NOT NULL,  
        name varchar(20) NOT NULL,
        sex int(2) NOT NULL,
        position varchar(20) NOT NULL,
        contact varchar(20) NOT NULL,
        rights  char(20) NOT NULL,
        loginnum varchar(20) NOT NULL  ,
        passnum varchar(20) NOT NULL  ,  
        PRIMARY KEY (id)
);

然后就可以插入数据了,如

insert into userinfo values (003 , '稀饭油条', 0,'会计','13407914258', '只能做账', '2200704515', '123456');

第三步:去官网下载mysql-connector-java-5.1.12压缩包,然后解压。

第四步:在Myeclipse里面新建一个.java文件,来测试数据库的连接,这代码可以参考刚才下载的包里面的docs里的connector-j.html,具体代码如下(注意修改database,user以及password):

import java.sql.Statement;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MysqlTestConnection {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Connection conn = null;
  Statement stmt = null;
  ResultSet rs = null;

  try {
            // The newInstance() call is a work around for some
            // broken Java implementations
            Class.forName("com.mysql.jdbc.Driver");
            conn =
                DriverManager.getConnection("jdbc:mysql://localhost/user1?" +
                                            "user=root&password=root");
          stmt=conn.createStatement();
          rs=stmt.executeQuery("select * from userinfo");
          while(rs.next()){
           System.out.println(rs.getString("name"));
          }
        } catch (ClassNotFoundException e) {
           e.printStackTrace();
        }
     
       
        
       catch (SQLException ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }
       finally {
         // it is a good idea to release
         // resources in a finally{} block
         // in reverse-order of their creation
         // if they are no-longer needed
         if (rs != null) {
             try {
                 rs.close();
             } catch (SQLException sqlEx) { } // ignore
             rs = null;
         }
         if (stmt != null) {
             try {
                 stmt.close();
             } catch (SQLException sqlEx) { } // ignore
             stmt = null;
         }

 

 }

}
}
第五步:最后点击项目,build path导入mysql-connector-java-5.1.12-bin.jar。最后就能从数据库里面取数据了!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值