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即可。


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

猜你喜欢

转载自blog.csdn.net/qq_38343647/article/details/80991678