statement语句

基本就是将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;
	}
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值