---
title: "数据库之二（错误异常）"
author: "linglingxia"
date: "2011-08-20T19:36:27Z"
tags: []
categories: ["数据库"]
slug: "untitled"
draft: false
lastmod: "2011-08-20T19:36:27Z"
id: 1154189
url: "https://linglxia.iteye.com/blog/1154189"
---

数据库的使用

1\. 要使用数据库，首先还是要连接数据库的。

连接数据库的步骤：

1加载驱动程序 2.创建指定数据库的URL  才能取得数据库连接对象。

就这个连接老犯错。

2\. 这里列几个常犯的错误

  ①没有引入外部mysql-connector-java-bin.jar包

 

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver  （没有找到这个类）

at java.net.URLClassLoader$1.run(Unknown Source)……

   所以在创建工程后，需要引入jar包

   ②.若加载驱动时，将com.mysql.jdbc.Driver写成com.mysql.jdbc.driver

   java.lang.ClassNotFoundException: com.mysql.jdbc.driver

   at java.net.URLClassLoader$1.run(Unknown Source)……

注意，以上两个报的是一样的异常

  ② .端口错误或者服务器没有启动

驱动不存在。。。。

com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:  

\** BEGIN NESTED EXCEPTION \**

java.net.ConnectException

MESSAGE: Connection refused: connect

STACKTRACE:

java.net.ConnectException: Connection refused: connect……

 

  ③ .主机localhost写错

com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: \** BEGIN NESTED EXCEPTION \**

java.net.UnknownHostException

MESSAGE: locahost（很明显的错误）

STACKTRACE:

java.net.UnknownHostException: locahost(未知的主机号)这个错误还好解决，提示很明显的。

 

   ④.加载驱动时，将com.mysql.jdbc.Driver  写成了com.mysql..jdbc.Driver

   java.lang.ClassNotFoundException: com/mysql//jdbc/Driver  （错误在这里得到提示）

   at java.lang.Class.forName0(Naticve Method)

   at java.lang.Class.forName(Unknown Source)

驱动不存在。。。。

  

   ⑤ 将数据库名写错（如test-&gt;tests）使用的是不存在的数据库

   com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Unknown database 'tests'（提示是未知的数据库）

   at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)……

驱动不存在。。。。

  

   ⑥.用户名或者密码错误

   java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

   at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:946)

   可以直接检查这两个是哪个的错误

 

   ⑦.数据库的url写错。如将

String url="jdbc:mysql:/localhost:3306/test";  写成了 String url="jdbc:mysql://localhost:3306/test";

错误提示：

java.sql.SQLException: No suitable driver found for jdbc:mysql:/localhost:3306/test驱动不存在。。。。

 

   ⑧.表名错误（数据库test中的stusinfo表不存在）

com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'test.stusinfo' doesn't exist

 

   ⑨.列名错误（age写成了ag,ag是不存在的）

com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Unknown column 'ag' in 'field list'

 

   ⑩.当取得数据库的结果集时，要获取的列号 6 大于数据库中的总列数5

java.sql.SQLException: Column Index out of range, 6 &gt; 5.

at com.mysql.jdbc.SQLError.createSQLException

(SQLError.java:910)

 

 我现在大概测试的异常也就这些，其他的还没想到，到时犯了才能注意吧。

在窗体上，点击按钮插入记录时，我还犯了一个错。当有新的记录插入时，我是将当前队列的size值+1作为它的id号，结果显示出来的是新的记录的id号比前面的还小（前面已经有些记录被删除了），当时也没在意这个问题。结果当测试写的弹出式菜单删除选择的记录时，才发现有问题，这样每次删除的记录并不是我真正要删除的。因为在上一步我就把他们的id号搞错了。原来当新插入一条记录时，id号时一直往下加的。即使是中间的记录删除了，其他记录的id号还是不会改变。 暂时还没做什么东西，所以犯错的机会也比较少啊……