java 连接数据库时发生的一些异常

第一次写博客  如果有不足之处请多指教

    相信大家在用java连接数据库对数据库进行更新查询的时候会遇到很多异常, 今天我们就来盘点一下java当中连接数据库时经常遇到的一些异常

1.     异常:java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).

  遇到这个异常一般是由于SQL中   ? 号 这里出现了错误

		Connection conn=DriverManager.getConnection(url,user,password);
			PreparedStatement pstmt=conn.prepareStatement("update course set Cname='?' , credit='?',introduce='?'");
			pstmt.setString(1, course.getcName());
			pstmt.setDouble(2, course.getCredit());
			pstmt.setString(3, course.getIntroduction());
如上语句  我们可以把它改为PreparedStatement pstmt=conn.prepareStatement("update course set Cname=? , credit=?,introduce=?");就可以啦   


2.  异常:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'age=20  where id=3' at line 1

                        Class.forName(driver);//注册驱动
			Connection conn =DriverManager.getConnection(url,user,upassword);//获取链接
			//预处理
			String sql="update tbl_student set name=?  age=?  where id=?";
			PreparedStatement pstmt=conn.prepareStatement(sql);
			pstmt.setNString(1, name);
			pstmt.setInt(2, age);
			pstmt.setLong(3, id);

这个异常时由于sql语句的错误引起的 ,只需要把红色标记位置改为 String sql="update tbl_student set name=? , age=?  where id=?";就可以解决  

3. 异常:java.sql.SQLException: Incorrect string value: '\xE5\xBC\xA0\xE4\xB8\x89' for column 'name' at row 1

StudentDao studentDao=new StudentDao();
		
		studentDao.updateById(3, "张三",20 );

这个异常时由于乱码引起来的  拿我的来说  我把自己的eclipse中改为了UTF-8编码  而我的mysql中的不是 ,这就导致了乱码 。

解决方案:重新安装一遍mysql  安装的时候把编码改为UTF-8即可。


纯属原创 ,如有雷同纯属巧合。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值