JDBC

第一步:加载驱动程序;
第二步:连接数据库;
第三步:访问数据库;
第四步:执行查询;

      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,这样从数据库查询的内容才是中文,否则乱码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值