无法从java app在数据库中创建表

时间:2012-12-13 17:55:19

标签: java mysql database

这是我的代码。只需从mySQL开始。 IDE是netbeans 7.2.1

    package monitordata;

    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import javax.xml.ws.Endpoint;


    public class monitorDataMF {

    public static void main(String[] args){
        Statement stmt = null;
        String dbname = null;
        String dbuser = null;
        String dbpass = null;
        String dbport = null;
        String dbIP = null;

        //pairnoume tis parametrous gia ti sindesi me ti vasi apo to properties file
        try{                
            Properties prop = new Properties();
            prop.load(new FileInputStream("mySQL.properties"));
            dbname = prop.getProperty("dbname");
            dbuser = prop.getProperty("dbuser");
            dbpass = prop.getProperty("dbpass");
            dbport = prop.getProperty("dbport");
            dbIP = prop.getProperty("dbIP");
        }catch(IOException e){e.printStackTrace();}

        //connecting with database
        try{
            Connection conn = null;
            Class.forName("com.mysql.jdbc.Driver");
            String dbUrl = "jdbc:mysql://" + dbIP + ":" + dbport + "/" + dbname;
            conn = DriverManager.getConnection(dbUrl, dbuser, dbpass);
            String createTable = "CREATE TABLE IF NOT EXISTS test"
                    + "(NAME VARCHAR(40) NOT NULL)";
            //String insertData = "INSERT INTO test "
            //        + "VALUES ('Stelios','Thwmas')";
            stmt = conn.createStatement();
            stmt.executeUpdate(createTable);
            //stmt.executeUpdate(insertData);
        }catch(ClassNotFoundException | SQLException e){}
    }
}

我执行更新,我转到服务> WebInterfaces 我点击刷新,桌子不在那里。我不确定我应该执行executeUpdate还是executeQuery

更新:        这是实际错误         捕获异常:用户'root'@'localhost'拒绝访问(使用密码:YES)  但我打印了我发送到连接语句的传递,它对应于数据库启动所需的传递。不确定我做错了什么

1 个答案:

答案 0 :(得分:1)

可能你会在执行时遇到错误,你没有在catch语句中记录异常。修改代码以查看错误。您还必须正确关闭连接。

   Connection conn = null;
 try{
        Class.forName("com.mysql.jdbc.Driver");
        String dbUrl = "jdbc:mysql://" + dbIP + ":" + dbport + "/" + dbname;
        conn = DriverManager.getConnection(dbUrl, dbuser, dbpass);
        String createTable = "CREATE TABLE IF NOT EXISTS test"
                + "(NAME VARCHAR(40) NOT NULL)";
        //String insertData = "INSERT INTO test "
        //        + "VALUES ('Stelios','Thwmas')";
        stmt = conn.createStatement();
        stmt.executeUpdate(createTable);
        //stmt.executeUpdate(insertData);
    }catch(ClassNotFoundException exp){
       System.err.println("Caught IOException: " + exp.getMessage()); 
    }catch( SQLException e) {
      System.err.println("Caught IOException: " + e.getMessage());
    } finally {
       if(conn != null) {
         conn.close();
       }
    }