postgresql 用java代码创建postgresql表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11626870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create postgresql Table in java code
提问by gadss
I have a code in java that connects with postgreSQL database.
我有一个与 postgreSQL 数据库连接的 java 代码。
now, I want that when it connects to the database, i will also create database table.
现在,我希望当它连接到数据库时,我还将创建数据库表。
but my problem is that, it will not create the database, and I don't know what is the problem.
但我的问题是,它不会创建数据库,我不知道是什么问题。
here is my code:
这是我的代码:
Statement st = null;
ResultSet rs = null;
try{
Class.forName("org.postgresql.Driver");
System.out.println("connect");
} catch (ClassNotFoundException cnfe){
System.out.println("Could not find the JDBC driver!");
System.exit(1);
}
Connection conn = null;
try {
//database location, database user, database password
conn = DriverManager.getConnection
("jdbc:postgresql:"POS_DB","postgres", "123456");
st = conn.createStatement();
String qs = "CREATE TABLE IF NOT EXISTS user(user_id SERIAL NOT NULL PRIMARY KEY,username varchar(225) NOT NULL UNIQUE,password varchar(225),islogged varchar(10))";
String qs1 = "SELECT * FROM test";
rs = st.executeQuery(qs);
System.out.println("connect");
} catch (SQLException sqle) {
System.out.println("Could not connect");
System.exit(1);
}
I am sure that my sql statement in creating the table is correct. but when I run this, it will not create the table. If I replace the string into select
sql, there is no problem.
我确定我在创建表时的 sql 语句是正确的。但是当我运行它时,它不会创建表。如果我将字符串替换为select
sql,则没有问题。
does anyone have an idea about my case?
有人知道我的案子吗?
thanks in advance ..
提前致谢 ..
回答by Michael Simons
you probably want to use a PreparedStatementlike so:
你可能想像这样使用PreparedStatement:
PreparedStatement ps = connection.prepareStatement("CREATE TABLE IF NOT EXISTS user(user_id SERIAL NOT NULL PRIMARY KEY,username varchar(225) NOT NULL UNIQUE,password varchar(225),islogged varchar(10))");
ps.executeUpdate();
ps.close();
You need executeUpdatefor DML and DDL statements.
对于 DML 和 DDL 语句,您需要executeUpdate。
Also, make sure your DDL statement is correct, i don't know the exact "if not exists" syntax for PostgreSQL
另外,请确保您的 DDL 语句是正确的,我不知道 PostgreSQL 的确切“如果不存在”语法
回答by alain.janinm
This line :
这一行:
conn = DriverManager.getConnection
("jdbc:postgresql:"POS_DB","postgres", "123456");
is invalid.
是无效的。
You have a "
before POS_DB that should'nt be here.
你有一个"
不应该在这里的 POS_DB 之前。
Too see some example check the documentation.
太看一些例子检查文档。
回答by John Masiello
postgresql 10 - 'user' is a keyword, thus not a good choice for a table. You will need a name that is not a reserved word.
postgresql 10 - 'user' 是一个关键字,因此不是一个表的好选择。您将需要一个非保留字的名称。