基于Myeclipse的数据库操作(非tomcat里导入驱动程序)
1>新建java Web项目 右键点击项目工程new->folder 起名lib(用来存放jdbc驱动程序)
2>找到驱动程序(mysql-connector-java-5.0.4-bin.jar)导入到lib中,右键点击驱动程序->build path->add build path,看到像奶瓶的文件就代表导入成功,即数据库驱动到此就可以用了
3>打开mysql
create database books;
create table book(name varchar(15),id int);
4>写程序进行增删改查(以java程序为例,java web里面写大同小异)
package com;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Scanner;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;
public class test {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Insert1(123456,"pan");
//Query1();
}
public static void Insert1(int id,String na) throws ClassNotFoundException, SQLException{
Connection conn=null;
Class.forName("com.mysql.jdbc.Driver");
conn=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/book","root","123456");
String sql="insert into b(name,id)values(?,?)";
PreparedStatement pst=(PreparedStatement) conn.prepareStatement(sql);
pst.setString(1,na);
pst.setInt(2,id);
pst.executeUpdate();
if(conn!=null){
conn.close();
}
}
public static void Query1() throws ClassNotFoundException, SQLException{
Connection conn=null;
Class.forName("com.mysql.jdbc.Driver");
conn=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/book","root","123456");
String sql="select * from b";
PreparedStatement pst=(PreparedStatement) conn.prepareStatement(sql);
ResultSet rs=(ResultSet) pst.executeQuery();
while(rs.next()){
int c=rs.getInt(2);
String name=rs.getString(1);
System.out.println(c+","+name+",");
}
if(conn!=null){
conn.close();
}
}
}
5>增加和查找编写成功了,以此为例