本人刚刚接触Java数据库编程,用的是eclipse+MySQL,我在以下第一个程序里面运行正常,程序如下:
import java.sql.*;
public class JDBCMysqlTest { /**
 * @param args
 * @throws ClassNotFoundException 
 */
public static void main(String[] args) throws ClassNotFoundException {
// TODO Auto-generated method stub
Connection connection;
try{
Class.forName("com.mysql.jdbc.Driver");  //装入JDBC驱动软件
String dbURL = "jdbc:mysql://localhost:3306";//数据库本机连接端口
//调用连接数据库方法,指定数据库,用户名,和密码
connection = DriverManager.getConnection(dbURL, "root", "wzc520168");
System.out.println("connection is succeeded...");
System.out.println("dbURL = " + dbURL);
System.out.println("connection = " + connection);
}
catch(SQLException e){
System.out.println("Error opening the db connection: " + 
                        e.getMessage());
} }}
(以上程序运行正常)
但是在如下程序运行时出现
Error opening the db connection:Can't create database 'productdb'; database exists的错误
源程序代码如下:
import java.sql.*;
public class JDBCMyaqlTest2 { /**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection connection;
try{
Class.forName("com.mysql.jdbc.Driver");
String dbURL = "jdbc:mysql://localhost:3306";
String username = "root";
String password = "wzc520168";
connection = DriverManager.getConnection(dbURL, "root", "wzc520168");
Statement stmt = connection.createStatement();
stmt.executeUpdate("create database ProductDB");  //创建数据库
stmt.executeUpdate("use ProductDB");  //使用指定的数据库
//创建数据库,VARCHAR是比CHAR更灵活的一种数据库类型,可存储变长的字符串;
//DECIMAL是SQL Server的数据类型,属于浮点型,10为有效长度,2为小数位数
stmt.executeUpdate("CREATE TABLE Products(" +
"Code CHAR(10), Title VARCHAR(40), Price DECIMAL(10, 2))");
stmt.executeUpdate("INSERT INTO Prdoucts VALUES(" + //插入数据
"'1100', 'Art in Java programming', 89.05)");
stmt.executeUpdate("INSERT INTO Products VALUES(" +
"'2200', 'Computer Color Printer', 1017.96)");
//选择记录
ResultSet rs = stmt.executeQuery("SELECT * FROM Products");
//得到记录
while(rs.next()){
String code = rs.getString("Code");
String title = rs.getString("Title");
double price = rs.getDouble("Price");
System.out.println("Code = "+code+" Title = "+title+" Price = "+price+"\n");
}
stmt.close();

}
catch(ClassNotFoundException e){
System.out.println("Database driver not found");
}
catch(SQLException e){
System.out.println("Error opening the db connection:"+ 
                        e.getMessage());
} }}
(我用的登录密码是我在安装Mysql时设置的,和我电脑的登录密码相同)
求大虾指教啊!!!

解决方案 »

  1.   

    Error opening the db connection:Can't create database 'productdb'; database exists已经存在了创建肯定失败。
    注释这句stmt.executeUpdate("create database ProductDB"); //创建数据库
    ,记得加上finally,在里面把连接给关了。
      

  2.   

    CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name [create_specification] ...加上这个
      

  3.   

    错误很清楚啊因为productdb这个名字的数据库已经存在了 你换一个名字试试 
    stmt.executeUpdate("create database ProductDB"); //创建数据库
    stmt.executeUpdate("use ProductDB"); //使用指定的数据库
    换个名字