eclipse平台连接mysql数据库,Eclipse连接MySQL数据库

本文详细介绍了如何在Eclipse中配置项目构建路径,将MySQL的jar包添加到库中,实现数据库连接。通过创建MysqlConnTest类,加载驱动并建立连接,展示了如何进行数据的读写操作。代码示例包括建立数据库、创建表以及测试读写方法。
摘要由CSDN通过智能技术生成

463b0c4c8ebf816480933be059f6c095.png

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

24f90b58bac51349394e4f457c5a734d.png

程序代码:

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;

运行结果:

a6f34b91d4139b5760e01cac2417542b.png

THE END

Eclipse连接MySQL数据库

标签:java   mysql

本条技术文章来源于互联网,如果无意侵犯您的权益请点击此处反馈版权投诉

本文系统来源:http://blog.csdn.net/some_times/article/details/46315739

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值