Câu hỏi của bạn hơi sai, với mã Java bạn không thể tạo cơ sở dữ liệu, bạn chỉ có thể kết nối với cơ sở dữ liệu.
Trước hết, bạn cần tạo cơ sở dữ liệu trong PgAdminIII.
Đây là mã mà sẽ giúp bạn tạo ra các bảng trong cơ sở dữ liệu postgresql qua JAVA
package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Database {
public static void main(String args[]) {
try {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/kanwar","postgres", "osm");
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName()+": "+e.getMessage());
System.exit(0);
}
System.out.println("Opened database successfully");
try {
stmt = c.createStatement();
} catch (SQLException ex) {
Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
}
String sql = "CREATE TABLE MY_TABLE "+
"(ID INT NOT NULL,"
+ "NAME TEXT NOT NULL,"
+ "AGE INT NOT NULL)";
stmt.executeUpdate(sql);
stmt.close();
c.close();
} catch (SQLException ex) {
Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
}
catch(Exception e)
{
System.err.println(e.getClass().getName()+": "+ e.getMessage());
System.exit(0);
}
System.out.println("Table Created Successfully");
}
}
Để tham khảo đầy đủ: http://kodingpoint.blogspot.in/2014/01/java-postgresql-connectivity-example.html
Nguồn
2014-02-10 18:01:37
FWIW, tôi sẽ không làm điều đó một phần trong Java. [Hướng dẫn] (http://www.postgresql.org/docs/9.1/interactive/tutorial.html) thảo luận về việc tạo DB, bảng, v.v. –
Và sau khi thiết lập cơ sở dữ liệu tôi chắc chắn bạn muốn biết cách để kết nối với cơ sở dữ liệu đó. [Tài liệu JDBC PostgreSQL] (http://jdbc.postgresql.org/documentation/head/index.html) sẽ cho bạn biết. –