1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.sql.*; import java.text.SimpleDateFormat; import java.util.Scanner;
public class JDBC20_demo { //定义MySQL的数据库驱动程序 public static final String DBDRIVER = "org.gjt.mm.mysql.Driver"; //定义MySQL数据库的连接地址 public static final String DBURL = "jdbc:mysql://localhost:3306/mysql_demo"; //MySQL数据库的连接用户名 public static final String DBUSER = "root"; //MySQL数据库的连接密码 public static final String DBPASS = "123456"; public static void main(String[] args) throws Exception{ // TODO 自动生成的方法存根 Connection conn = null; //数据库连接 PreparedStatement pstmt = null; //数据库操作 ResultSet rs = null; //保存结果集 String sql = "SELECT id,name,password,age,sex,birthday "+ " FROM user WHERE id=?"; Class.forName(DBDRIVER); //加载驱动程序 //连接MySQL数据库时,要写上连接的用户名和密码 conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS); //实例化PreparedStatement pstmt = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); pstmt.setInt(1, 2); //更新3号用户 rs = pstmt.executeQuery(); //实例化ResulitSet对象 rs.last(); //移动到最后一行 rs.updateString("name", "王小明"); rs.updateString("password", "wangxiaoming"); rs.updateInt("age", 24); rs.updateString("sex", "男"); rs.updateDate("birthday", new java.sql.Date(new java.util.Date().getTime())); rs.updateRow(); //更新数据 rs.close(); //关闭结果集 pstmt.close(); conn.close(); }
public static void print(ResultSet rs,int re) throws Exception{ if(re>0){ rs.next(); //由前向后输出 }else{ rs.previous(); //有后向前输出 } int id = rs.getInt(1); String name = rs.getString(2); String pass = rs.getString(3); int age = rs.getInt(4); String sex = rs.getString(5); java.util.Date d = rs.getDate(6); System.out.println("编号:"+ id); System.out.println("姓名:"+name); System.out.println("密码:"+pass); System.out.println("年龄:"+age); System.out.println("性别:"+sex); System.out.println("生日:"+d); } }
|