Java连接MySQL 建表的时候出错了

sheep902 发布于 2014/04/06 17:01
阅读 447
收藏 0

DBManager类

--------------------------------------------------

package com.atu.xmltest;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


public class DBManager{


static Connection conn=null; 
 static{
  System.out.println("in DBManager");
  String dbName="test";
  try{
   Class.forName("com.mysql.jdbc.Driver");
   //配置数据源
   String url="jdbc:mysql://183.129.17.10/"+ dbName +
         "?useUnicode=true&characterEncoding=GB2312";
       conn=DriverManager.getConnection(url,"root","123456");
       }catch(Exception e){
        System.out.println("Exception:"+e.getMessage());
   }
 }
 
 public synchronized static Connection getConnection(){
  Connection temp=null;
  if(conn!=null){
   temp=conn;
   conn=null;
   return temp;
  }else{
   return null;
  }
  
 }
 
 public synchronized static void releaseConnection(Connection con){
   conn=con;
  }
 
 public static void closeConn(){
  try{
   conn.close();
  }catch(SQLException e){
   System.out.println(e.getMessage());
   }
  }
 
 
}
--------------------------------------------------------------

WriteIntoDB类

---------------------------------------------------

package com.atu.xmltest;


import java.sql.SQLException;


import com.mysql.jdbc.PreparedStatement;






public class WriteIntoDB extends DBManager{

public static void main(String[] args) throws SQLException {
   new DBManager();
     //  new MySaxHandler();
       try {
        Createtable();    //编译器提示错误的地方
       } catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
       }
   }
 
public static void Createtable() throws SQLException, ClassNotFoundException
{
String sql = "CREATE TABLE test ("
     + "id int not null, name varchar(20) not null, "
     + "age int null, "
     + "primary key (id)"
     + ");";


PreparedStatement pstmt = (PreparedStatement) conn.prepareStatement(sql);  //编译器提示错误的地方
pstmt.executeUpdate();


}
 
}



---------------------------------------------------------------------

出错提示

in DBManager
Exception:Access denied for user 'root'@'ZGC-20140301GVE' (using password: YES)
Exception in thread "main" java.lang.NullPointerException
at com.atu.xmltest.WriteIntoDB.Createtable(WriteIntoDB.java:30)
at com.atu.xmltest.WriteIntoDB.main(WriteIntoDB.java:15)

求技术大牛解答

加载中
0
LiShixi
LiShixi


Connection conn = getConnection();

看下getConnection()方法是不是正确创建了Connection 对象

可能是连接数据库的参数写错了吧。


sheep902
sheep902
回复 @LiShixi : 问题解决了。貌似是IP和端口的问题。谢谢你的回答
LiShixi
LiShixi
好好看看你的getConnection方法吧。 调试进去看看conn是不是null
sheep902
sheep902
还是不行呀。。。我把源码都贴出来,你看看
0
hibegin
hibegin
端口是80? 不是3306?
sheep902
sheep902
我把ip换成localhost就编译通过了。谢谢
0
sheep902
sheep902

引用来自“wzfz”的评论

端口是80? 不是3306?

谢谢

返回顶部
顶部