码迷,mamicode.com
首页 > 数据库 > 详细

Eclipse连接MySQL数据库

时间:2015-06-01 22:44:20      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:java   mysql   

工作目录:

技术分享

右键项目,选中Build Path,选中configure build path,把lib目录下的jar包加入路径。
技术分享

程序代码:
package com.test;
import java.sql.*;//引入包
public class MysqlConnTest {
      public MysqlConnTest() {
            status = -1;
           setConnection( null);
            try {
                Class. forName( "com.mysql.jdbc.Driver"); //加载驱动
                setConnection(DriverManager. getConnection( "jdbc:mysql://localhost:3306/test", "root", "123456")); //建立连接
           } catch (Exception e) {
                 e.printStackTrace();
           }
            status = 1;
     }
     
      public static void main(String args[]) throws SQLException{
           MysqlConnTest instance = new MysqlConnTest();
            if ( instance.getStatus() == 1) {
                 //状态准备好了
                 instance.TestWrite();
                 instance.TestRead();
                
                 instance.getConnection().close();
           }
     }
     
      //测试写程序
      public void TestWrite() throws SQLException{
           PreparedStatement statement = getConnection().prepareStatement("insert into test(name) values ('hello')");
            statement.executeUpdate();
     }
     
      //测试读程序
      public void TestRead() throws SQLException{
           PreparedStatement statement = getConnection().prepareStatement("select * from test" );
           ResultSet result = statement.executeQuery();
            while( result.next()){
                System. out.println( "id = " + result.getInt(1) +",name = " + result .getString(2));
           }
            result.close();
     }
     
      private int status;
      private Connection connection;
     
      public int getStatus(){
            return status;
     }
     
      public void setStatus( int status){
            this. status = status;
     }

      public Connection getConnection() {
            return connection;
     }

      public void setConnection(Connection connection) {
            this. connection = connection;
     }
}
SQL文件:
CREATE DATABASE  IF NOT EXISTS `test`;
USE `test`;
DROP TABLE IF EXISTS `test`;
CREATE TABLE `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
运行结果:
技术分享

THE END

Eclipse连接MySQL数据库

标签:java   mysql   

原文地址:http://blog.csdn.net/some_times/article/details/46315739

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!