java JDBC操作MySQL数据库
一,首先在MYSQL建立一个数据库,例如Geek99DB:
create database Geek99DB;
use Geek99DB;
然后建立一个表CustomerTab:
create table CustomerTab(id int primary key auto_increment,name varcahr(20),email varchar(20));
显示表:
show tables;
添加元素:
insert into CustomerTbl(name,email)values('tam','123@qq.com');
显示元素:
select *from CustomerTbl;
二,在ecplise下完成对数据库的获取:
首先,建立一个java项目,新建一个文件夹lab,将mysql-connector-java-5.1.22-bin.jar(JDBC的驱动程序,复制到此文件夹下,并添加到build path);
然后新建一个class文件,代码如下:
package jdbctest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class test01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//加载JDBC驱动
Connection conn=null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//连接到特定的数据库对象
try {
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/Geek99DB","root","yuan");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//建立SQL语句对象,执行查询
String sql="select id,name,email from CustomerTbl";
try {
Statement stmt =conn.createStatement();
ResultSet rs=stmt.executeQuery(sql);
//处理结果集
while(rs.next()){
int id=rs.getInt(1);
String name=rs.getString(2);
String email=rs.getString(3);
System.out.println(id+","+name+","+email);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//关闭数据连接
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}finally {