用Java代码创建Postgresql表 [英] Create postgresql Table in java code
问题描述
我在Java中有一个与postgreSQL数据库连接的代码。
现在,我希望当它连接到数据库时,我还将创建数据库表。 / p>
但是我的问题是,它不会创建数据库,而且我也不知道是什么问题。
这是我的代码:
Statement st = null;
ResultSet rs = null;
try {
Class.forName( org.postgresql.Driver);
System.out.println( connect);
} catch(ClassNotFoundException cnfe){
System.out.println(找不到JDBC驱动程序!);
System.exit(1);
}
连接conn = null;
try {
//数据库位置,数据库用户,数据库密码
conn = DriverManager.getConnection
( jdbc:postgresql: POS_DB, postgres, 123456 );
st = conn.createStatement();
字符串qs =如果用户不存在则创建表(user_id SERIAL NOT NULL PRIMARY KEY,用户名varchar(225)NOT NULL UNIQUE,密码varchar(225) ,islogged varchar(10));
字符串qs1 = SELECT * FROM test;
rs = st.executeQuery(qs);
System.out.println( connect);
} catch(SQLException sqle){
System.out.println(无法连接);
System.exit(1);
}
我确定创建表的sql语句是正确的,但是当我运行它时,它将不创建表。如果我将字符串替换为 select
sql,就没有问题。
有人对我的案子有想法吗?
预先感谢..
此行:
conn = DriverManager.getConnection
( jdbc:postgresql : POS_DB, postgres, 123456);
无效。
您有一个
不应位于POS_DB之前。
也看到一些示例,请检查文档。
I have a code in java that connects with postgreSQL database.
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.
does anyone have an idea about my case?
thanks in advance ..
This line :
conn = DriverManager.getConnection
("jdbc:postgresql:"POS_DB","postgres", "123456");
is invalid.
You have a "
before POS_DB that should'nt be here.
Too see some example check the documentation.
这篇关于用Java代码创建Postgresql表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!