1 数据连接和创建表格
package create_table_system; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import dbutil.DBUtil; //建立表格建立表格建立表格建立表格 public class CreateTable { public static void main(String[] args) { Table(); } public static void Table(){ //调用 DBUtil() 方法 Connection conn = DBUtil.open(); //建立数据库语句 String str ="create table jj ( " + "Sno char(9) primary key, " + "Sname char(10) unique, " + "Ssex char(2), Sage smallint, " + "Sdept char(20) )"; try { //Statement类 Statement sta = conn.createStatement(); //execute sta.execute(str); } catch (Exception e) { e.printStackTrace(); } } }
2 数据库插入
package create_table_system; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import dbutil.DBUtil; public class Insert { public static void main(String[] args){ Connection conn = DBUtil.open(); try { Statement sta = conn.createStatement(); String str = "INSERT INTO `goddess` VALUES " + "('11', 'mei', '1', '22', '2015-12-12', " + "'[email protected]', '13911111111', 'ADMIN', " + "'2015-01-08', 'ADMIN', '2015-01-08', '0')"; //这不是executeUpdata sta.execute(str); //关闭资源 sta.close(); conn.close(); DBUtil.close(conn); } catch (SQLException e) { e.printStackTrace(); }finally{ System.out.println("已经插入数据!"); } } }<span style="color:#ff0000;"> </span>3 数据库查询
package create_table_system; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import dbutil.DBUtil; //查询数据库!查询数据库!查询数据库! public class Search { public static void main(String[] args) { try { Connection conn = DBUtil.open(); //第三步:通过数据库的连接操作数据库,实现功能。 Statement sta = conn.createStatement(); ResultSet res = sta.executeQuery("select user_name,age,birthday," + "email,mobile from goddess "); //循环查询 while(res.next()){ System.out.println( res.getString("user_name") +" " + res.getString("age") +" " + res.getString("birthday") +" " + res.getString("email") +" " + res.getString("mobile") +" " ); } //关闭资源 res.close(); sta.close(); //关闭数据库连接 DBUtil.close(conn); } catch (SQLException e) { System.out.println("您好!驱动加载失败!"); }finally{ System.out.print("查询方法已经执行"); } } }
package create_table_system; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import dbutil.DBUtil; //数据库修改 public class Modify { public static void main(String[] args) { ModifyTo(); } public static void ModifyTo(){ Connection conn = DBUtil.open(); try { Statement sta = conn.createStatement(); String sql = "update goddess set user_name='程序员' where id=2 "; sta.executeUpdate(sql); //关闭资源 sta.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); }finally{ System.out.println("数据已经修改成功!"); } } }