Java uses JDBC to remotely connect to PostgreSQL and implement operations

Tools and preparation introduction:

1. The development software used in this article is eclipse1.7
2. You need to download postgresqlpostgresql-9.2-1002.jdbc3.jar (if necessary, download it from my resources); you need the database management software Navicat
3. This article uses JDBC to connect to the database, through Read the ".sql" file to implement query and insert operations on the Postgresql database

Implementation steps

1. First connect to the database remotely

(1) Open the database management software Navicat, click the connection in the upper left corner, and select PostgreSQL.

insert image description here
(2) Fill in the connection information. Here you only need to fill in the connection name and password (the password set when installing PgSQL), and the others are default. localhost is the address of the local machine (fill in its IP address for the remote connection), and 5432 is the port of the PgSQL database. After filling in the connection information, click Test Connection. If the connection is successful, the dialog box indicates that PgSQL Server is started. Click OK to complete the connection to the PgSQL database.
insert image description here
After the connection is complete, you will see the connection information on the left. The postgres under the Bolisen subdirectory is an initial PgSQL database that can be used directly. You can also select postgres, right-click and select New Database to create a new PgSQL database.
insert image description here

Insert a sentence (if the project jar package will import the layout, please ignore this article)

The creation of the java project before the start is omitted, and I will post my simple project diagram below: ! If the jar package is imported: create a new lib (with any name) folder and put the downloaded jar package in it –> right-click the jar package –> click Build Path --> Then you click on the first one to rebuild it, and it will enter the Referenced Libraries (see Figure 1). The dao package mainly writes the data insertion method; the Demo package is the test code; the util package is a toolkit, and writes the method of connecting to the database. Insert the picture description here
Figure 1:insert image description here

2. Start writing Java code

2.1 First connect to the database (configuration file connection)

(1) Create a .properties file under the project, such as the dbcpconfig.properties file in this article, the file name can be chosen by yourself, and paste the content of my configuration file below:

driver=org.postgresql.Driver
url=jdbc:postgresql://10.167.81.11:27500/postgres?characterEncoding=utf-8
username=user
password=zzr1100!

<!-- \u521D\u59CB\u5316\u8FDE\u63A5 -->
initialSize=10
<!--\u6700\u5927\u8FDE\u63A5\u6570\u91CF  -->
maxActive=50
<!-- \u6700\u5927\u7A7A\u95F2\u8FDE\u63A5 -->
maxIdle=20
<!-- \u6700\u5C0F\u7A7A\u95F2\u8FDE\u63A5 -->
minIdle=5
<!-- \u8D85\u65F6\u7B49\u5F85\u65F6\u95F4\u4EE5\u6BEB\u79D2\u4E3A\u5355\u4F4D 6000\u6BEB\u79D2/1000\u7B49\u4E8E60\u79D2 -->
maxWait=60000在这里插入代码片

Note: The following parameters of initialization size and maximum capacity must be written, otherwise the connection will not work
(2). The Java code for connecting to the database is as follows:

public class JDBCUtils {
	       private static Properties prop;
	       static {
	              prop = new Properties();
	              try {
	                    InputStream is= JDBCUtils.class.getClassLoader().getResourceAsStream(
	                                   "dbcpconfig.properties");
	                    prop.load(is);               
	                     Class.forName(prop.getProperty("driver"));//加载驱动
	              } catch (Exception e) {
	            	  	System.out.println("出错了");
	                     throw new RuntimeException(e);
	                     
	              }
	       }
	       //获取连接
	       public static Connection getConnection(Connection conn) {
	              if (conn==null) {
	                     try {
	                            conn=DriverManager.getConnection(prop.getProperty("url"),
	                            prop.getProperty("username"),
	                            prop.getProperty("password"));
	                     } catch (SQLException e) {
	                            throw new RuntimeException(e);
	                     }
	              }
	                return conn;   
	       }
	       //关闭资源
	       public static void close(Connection conn,PreparedStatement prep,ResultSet rs){
	        if(rs != null){
	            try {
	                rs.close();
	            } catch (SQLException e) {
	                e.printStackTrace();
	            } finally{
	                rs = null;
	            }
	        }
	        if(prep != null){
	            try {
	                prep.close();
	            } catch (SQLException e) {
	                e.printStackTrace();
	            } finally{
	                prep = null;
	            }
	        }
	        if(conn != null){
	            try {
	                conn.close();
	            } catch (SQLException e) {
	                e.printStackTrace();
	            } finally{
	                conn = null;
	            }
	        }
	    }
	       public static void close(Connection conn,PreparedStatement prep){
	    	   if(prep != null){
		            try {
		                prep.close();
		            } catch (SQLException e) {
		                e.printStackTrace();
		            } finally{
		                prep = null;
		            }
		        }
		        if(conn != null){
		            try {
		                conn.close();
		            } catch (SQLException e) {
		                e.printStackTrace();
		            } finally{
		                conn = null;
		            }
		        }
	       }
}
在这里插入代码片

2.2 Create a .sql file, read the file and perform the insert operation

(1) This article uses the insert operation as an example to illustrate: create a sqlfile (with any name) folder as shown in the figure below, and then create a new .sql file, which contains the sql statement you want to insert data (note that I only wrote one line of insert statement here) For testing, if you write a multi-line insert statement, you need to add logic code yourself) Attach the sql statement example in this article for reference
insert image description here

INSERT INTO hxdb.person( name, age, sex)VALUES (?, ?, ?)

(2) Java reads sql file implementation

public class FileReader {
	
	    public static String readText() {
	    	String filePath="sqlfile/insert.sql";
	    	StringBuilder sb=new StringBuilder();
	        //通过路径创建文件
	        File file = new File(filePath);     
	        if (file.isFile() && file.exists()) {
	            try( //文件编码为gbk,这里做个转换
		                InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
		                //字符缓冲流
		                BufferedReader br = new BufferedReader(isr);) {              
	            		String line=null;               
	                while ((line = br.readLine()) != null) {            	
	                	sb.append(line);					
	                }
						             
	            } catch (IOException e) {
	                e.printStackTrace();
	                System.out.println("文件读取错误!");
	            }
	        }else {
	            System.out.println("文件不存在!");
	        }
	        return sb.toString();
	    }	   
}

(3) Insert data operation method class with reference to this article (the Symfware class in this article mainly encapsulates these methods for query insertion, and you can choose the actual class name according to the project)

public class Symfware {
	PreparedStatement ps = null;
	Connection con=null;
	ResultSet resultSet=null;
	int result=0;
	//1.查询person表中所有内容
	public void selectPerson(String line) {
		 con=JDBCUtils.getConnection(con);//连接数据库
		try {
			
			 ps=con.prepareStatement(line);
			System.out.println(ps);
			 resultSet=ps.executeQuery();
			while (resultSet.next()) {
				String id = resultSet.getString("name");       //读取当前行名为id的列的数据
	             int age1 = resultSet.getInt("age");
	            // int sex1 = resultSet.getInt("sex");​
	             //System.out.println("name:"+id+"age:"+age1);		
			}
			
		} catch (SQLException e) {
	
			e.printStackTrace();
		}finally {
			JDBCUtils.close(con, ps,resultSet);
		}
			
	}
	
	//2.插入 sql 操作
	public int insertContent(String name,int age,int sex ) {
		
		String sql=FileReader.readText();//读取到的sql
		con=JDBCUtils.getConnection(con);
		
		try {
			con.setAutoCommit(false);
			ps=con.prepareStatement(sql);
			ps.setString(1, name);
			ps.setInt(2, age);
			ps.setInt(3, sex);
			result=ps.executeUpdate();
			 System.out.println(result + "11111多少行");
			 con.commit();
		} catch (SQLException e) {
			e.printStackTrace();
			
		}finally {
			JDBCUtils.close(con, ps);
		}	
		return result;
	}
}

2.3 Finally reached the last step, the test results

Paste the test example of this article below

public class Test1 {
	public static void main(String[] args) {
	
		 Symfware symfware=new Symfware();
		 symfware.insertContent("1111", 1238, 0);
		
	}	
}

okay! Thanks for watching, I hope it helps you

Digression: Hahaha, this csdn blog post of mine is still a short period of homework I experienced when I entered a project team in July after graduation this year. It took me a long time to think about recording it. No mistake (hahaha) If there is any problem, please forgive me! Thanks

Guess you like

Origin blog.csdn.net/weixin_51553816/article/details/125633200