statement语句
2016-03-11 15:20
399 查看
基本就是将sql语句封装进函数里,
testdemo2.java如下
lib.java如下
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; } }
相关文章推荐
- JAVA程序中如何调用C/C++方法
- 2-1-1 GDI
- thinkPHP volist标签循环输出多维数组
- SQL Server T-SQL高级查询
- 让PHP7达到最高性能的几个Tips(转)
- Josephus问题
- java 遍历Map的四种方法
- tuxedo 安装,运行示例。(解决遇到的问题)
- updating local specs repositories卡住
- [Bundling and Minification ] 一、如何绑定
- POJ 1125-Stockbroker Grapevine-最短路
- redis 学习指南
- 回调函数
- iOS之对象归档
- PAT (Advanced Level) Practis 1039 Course List for Student (25)
- Android 基于google Zxing实现二维码、条形码扫描,仿微信二维码扫描效果
- 【iOS】点击按钮获取验证码控件
- 《Visual c++从初学到精通》读书笔记(1)
- advanced backend configuration(后端服务器高级配置)
- DIV的变高与变宽