基本就是将sql语句封装进函数里,
testdemo2.java如下
package my_sql_test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class testdemo2 {
public static void main(String[] args){
// createTable();
// insert();
// update();
// delete();
query();
}
static void insert(){
Connection conn=DBUtil.open();
String sql="insert into lib(book) values ('hi'),('mi');";
try {
Statement stmt=conn.createStatement();
stmt.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBUtil.close(conn);
}
}
static void update(){
Connection conn=DBUtil.open();
String sql="update lib set book='xi' where book='mi';";
try {
Statement stmt=conn.createStatement();
stmt.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBUtil.close(conn);
}
}
static void delete(){
Connection conn=DBUtil.open();
String sql="delete from lib where book='xi';";
try {
Statement stmt=conn.createStatement();
stmt.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBUtil.close(conn);
}
}
static List<lib> query(){
Connection conn=DBUtil.open();
String sql="select * from lib";
try {
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery(sql);
List<lib> list =new ArrayList<lib>();
while(rs.next()){
int id=rs.getInt(1);
String book=rs.getString(2);
//System.out.println(book);
lib l=new lib();
l.setId(id);
l.setBook(book);
list.add(l);
}
System.out.println(list);
return list;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBUtil.close(conn);
}
return null;
}
static void createTable(){
Connection conn=DBUtil.open();
String sql="create table lib(id int primary key auto_increment,book text);";
try {
Statement stmt=conn.createStatement();
stmt.execute(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBUtil.close(conn);
}
}
}
lib.java如下
package my_sql_test;
public class lib {
private int id;
private String book;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public String toString(){
return id+":"+book;
}
}