本文实例讲述了java使用jdbc连接postgresql数据库。分享给大家供大家参考,具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
package tool;
import java.sql.connection;
import java.sql.drivermanager;
import java.sql.preparedstatement;
import java.sql.resultset;
import java.sql.sqlexception;
public class psqlconnectiontool {
private string url = "jdbc:postgresql://xxx.xxx.xxx.xxx:5432/testdb" ;
private string username = "postgres" ;
private string password = "postgres" ;
private connection connection = null ;
public connection getconn() {
try {
class .forname( "org.postgresql.driver" ).newinstance();
connection = drivermanager.getconnection(url, username, password);
} catch (instantiationexception e) {
// todo auto-generated catch block
e.printstacktrace();
} catch (illegalaccessexception e) {
// todo auto-generated catch block
e.printstacktrace();
} catch (classnotfoundexception e) {
// todo auto-generated catch block
e.printstacktrace();
} catch (sqlexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
return connection;
}
public resultset query(connection conn, string sql) {
preparedstatement pstatement = null ;
resultset rs = null ;
try {
pstatement = conn.preparestatement(sql);
rs = pstatement.executequery();
} catch (sqlexception e) {
e.printstacktrace();
}
return rs;
}
public boolean queryupdate(connection conn, string sql) {
preparedstatement pstatement = null ;
int rs = 0 ;
try {
pstatement = conn.preparestatement(sql);
rs = pstatement.executeupdate();
} catch (sqlexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
if (rs > 0 ) {
return true ;
}
return false ;
}
public static void main(string[] args) throws sqlexception {
psqlconnectiontool pgtool = new psqlconnectiontool();
connection myconn = pgtool.getconn();
pgtool.queryupdate(myconn, "insert into test values (1,'smoon','man')" );
resultset rs = pgtool.query(myconn, "select * from test" );
while (rs.next()){
int id = rs.getint( "id" );
string name = rs.getstring( "name" );
string gender = rs.getstring( "gender" );
system.out.println( "id:" +id+ " 姓名:" +name+ " 性别:" +gender);
myconn.close();
}
}
}
|
希望本文所述对大家java程序设计有所帮助。
原文链接:https://blog.csdn.net/s465689853/article/details/81217448