Java高手请进,谢谢!急救

来源:百度知道 编辑:UC知道 时间:2024/05/31 11:35:58
我写了两个类:
第一个类:(是数据库MySQL连接):
public class HtConnection {
public static Connection getConnection() {
String myUrl="jdbc:mysql://localhost:3306/test";
String userName="root";
String userPaw="123";
Connection con=null;
String driverName="com.mysql.jdbc.Driver";
try{
Class.forName(driverName);
con=DriverManager.getConnection(myUrl,userName,userPaw);
System.out.println("数据库接连成功!");
//con.close();
return con;
}
catch(ClassNotFoundException cnfex){
System.err.println("装载JDBC 驱动程序失败。" );
cnfex.printStackTrace();
System.exit( 1 );
return null;
}
catch(SQLException sqlex){
System.err.println( "无法连接数据库" );
sqlex.printStackTrace();
System.exit( 1 );
return null;
}

}

第二个类:(建表)
public class SetupDB {
public static boolean setupDB() {

Class.forName("驱动");
Connection con=DriverManager.getConnection(url,username,password);

即可联上数据库,然后就是Statement了

连接数据库在main里面 HtConnection hc = new HtConnection (); hc.getConnection();或
HtConnection.getConnection();
建表 同理 SetupDB sd = new SetupDB ();

第二个类里已经调用了第一个类来连接,所以你就不用再调了。

可以直接SetupDB.setupDB(),不过里面的cleardb()方法是怎么回事没看出来