myeclipse 连接mysql

方法1:用户界面连接数据库

步骤:参考

http://jingyan.baidu.com/article/4e5b3e196758ad91901e24a0.html

 

但是这样有一些问题:(1)Table/Object Info 出现错误;解决办法:把project下的build automatically前面的勾去掉,然后重新启动MyEclipse即可;

(2)数据库中的数据表可以创建,但是不能编辑;在数据库 MySQL5.6 Command Line Client中创建table student。

createdabase database testmysql;

show databases;

use testmysql;

create table student(id int(3),name char(10));

insert into student values(‘1’,’zhangsan’);

insert into student values(‘2’,’lisi’);

select * from student;

这样建立的table student在myeclipse连接mysql后不能对这个数据库表student不能编辑,即右击student-edit data 会出现Error:Cannot edit:The result set is not updatable;

解决方法:在创建表格的时候,参数值中设置主键。把create table student(id int(3),name char(10));改成create table student(id int(3) primary key,name char(10));这样建立的table 就可以对其进行编辑。

 

方法2:使用代码连接数据库

(1)     新建java project(TestJBDC)——>新建class文件JDBCExample;

(2)     JDBC配置

Window-preferences-java-build path 在user libraries列表中,单击new,新建一个名为MySQL(自己随便定义)的user libraries name;注意:下面的复选框不要选,否则libraries会成为系统默认的libraries;然后“Add JARS”把mqlde 驱动程序Connector/J添加进来。

(3)     在本项目在加载JDBC.右击项目java project(TestJBDC)->build path->Add libraries->user libraries->next->MySQL(刚刚在JDBC配置中新建的)。

(4)     编写JDBCExample,编译运行。代码如下:

import java.sql.DriverManager;

import java.sql.Connection;

import java.sql.Statement;

import java.sql.ResultSet;

import java.sql.SQLException;

 

public class JDBCExample {

 

 

         public static void main(String[] args)

         {

                   try

                   {                 //加载mysql数据库驱动程序

                            Class.forName("com.mysql.jdbc.Driver");

                       String url = "jdbc:mysql://localhost:3306/testmysql?user=root&password=mysql";

                       Connection conn = DriverManager.getConnection(url);//建立连接对象;

                       Statement stmt = conn.createStatement();//建立陈述对象;

                       ResultSet rs = stmt.executeQuery("select * from stu");//返回ResultSet对象;

                       //遍历ResultSet对象汇总的各个字段;

while(rs.next())

                       {

                                     System.out.print("学生的学号: " + rs.getInt(1));

                                     System.out.println("\t学生的名字: " + rs.getString(2));

                                     //System.out.println("\t学生的性别: " + rs.getBoolean(3));                                                           

                            }

                            rs.close();

                            stmt.close();

                            conn.close();

                   }

                  

                   catch(ClassNotFoundException e)

                   {

                       System.out.println("找不到指定的驱动程序类!");

                   }

                  

                   catch(SQLException e)

                   {

                       e.printStackTrace();

                   }

posted on 2014-04-01 17:07  growAriel  阅读(368)  评论(0编辑  收藏  举报