第一步:加载驱动程序;
第二步:连接数据库;
第三步:访问数据库;
第四步:执行查询;
Connection conn = null;
PreparedStatement ps=null; 或 Statement stmt = null;
ResultSet res = null;
String sql =xxxxxxxxx;
Class.forName(“com.mysql.jdbc.Driver”);
conn=DriverManager.getConnection(“jdbc:mysql://localhost:3306/student?characterEncoding=utf8”,“root”,“abc123”);
ps=conn.prepareStatement(sql); 会预编译 或 stmt=conn.createStatement()
res=ps.executeQuery(); 查询用这个。 修改或添加或删除用ps.execute() 或 ps.executeUpdate()
如果stmt=conn.createStatement()则res=stmt.executeQuery(sql); 查询用这个 。修改或添加或删除用 stmt.execute(sql) stmt.executeUpdate(sql)
---------------------------------------------------------------------------------------------------
ResultSet 有getString() 和getInt() 和next() 方法 ,比如
Connection conn = null;
PreparedStatement ps = null;
ResultSet res = null;
conn=DriverManager.getConnection(“jdbc:mysql://localhost:3306/student?characterEncoding=utf8”,“root”,“abc123”);
ps = conn.prepareStatement(sql);
res = ps.executeQuery();
res.next();
String a = res.getString(2);
getString(2)显示的是第二列,这个方法是选择列的。res.next()指针指向下一条记录,执行一次res.next()就跳到下一行。一开始必须使用一次 res.next(),才指向第一行的数据。不然直接gerString()是没数据的。res.next是boolean,没数据则返回false,有则true,所以可以用 while (res.next())
-----------------------------------------------------------------------------------------------------
PreparedStatement 有setInt 和setString 方法 如: ps.setString(1,“插入信息”)
-----------------------------------------------------------------------------------------------------
编码的问题 conn=DriverManager.getConnection(“jdbc:mysql://localhost:3306/renting?characterEncoding=utf8”,“root”,“abc123456”); 添加了characterEncoding=utf8才可以添加中文或者修改中文到数据库,否则乱码。
同理,数据库中内容是中文的数据项必须设置utf8_general_ci,这样从数据库查询的内容才是中文,否则乱码