Eclipse连接MySQL数据库
来源:互联网 发布:微信恶搞软件安卓 编辑:程序博客网 时间:2024/05/16 07:03
工作目录:
右键项目,选中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
0 0
- Eclipse连接MySQL数据库
- Eclipse连接MySQL数据库
- Eclipse连接MySQL数据库
- Eclipse连接MySQL数据库
- Eclipse连接MySQL数据库
- eclipse连接mysql数据库
- Eclipse连接MySQL数据库
- eclipse连接mysql数据库
- eclipse连接mysql数据库
- Eclipse连接MySQL数据库
- eclipse连接mysql数据库
- Eclipse连接MySQL数据库
- Eclipse连接MySQL数据库
- Eclipse连接MySQL数据库
- eclipse 连接 mysql 数据库!
- Eclipse 连接MySql数据库
- eclipse连接MySQL数据库
- eclipse连接MySQL数据库
- 贪心算法—活动选择问题
- Apache虚拟主机及别名配置
- 内核模块开发
- 单例模式(Singleton Pattern)
- 项目管理修炼之道(二 规划项目)
- Eclipse连接MySQL数据库
- Leetcode Contains Duplicate
- 线程
- zookeeper原理
- JavaScript-break 语句用于跳出循环
- 基于 C++ Primer 5 的 C++ 学习笔记(一) — 变量与基本数据类型总结
- quick-cocos2d 之动态更新
- Redhat下R安装Rwordseg包
- webservice入门之CXF教程 helloworld