这篇文章主要介绍了Java使用JDBC连接postgresql数据库,结合实例形式分析了jdbc连接postgresql数据库及数值插入、更新、查询等相关操作技巧,需要的朋友可以参考下
本文实例讲述了java使用jdbc连接postgresql数据库。分享给大家供大家参考,具体如下: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
|