testdb.java

来自「--- -----测试数据库连接的java程序」· Java 代码 · 共 42 行

JAVA
42
字号
import java.sql.*;
public class TestDB{
	public	static void main(String args[])
	{
	try
	{
	Class.forName("org.postgresql.Driver");
	String url="jdbc:postgresql://localhost:5432/postgres";//连接本地postgresql数据库服务器,连接的数据库名伟postgres
	
	Connection con=DriverManager.getConnection(url,"postgres","cAndc++");	
	
	Statement st=con.createStatement();
	String SQLstr="select * from abc";//需要postgres数据库中有abc表
	
	ResultSet rs=st.executeQuery(SQLstr);
	while (rs.next())
	{
	System.out.print(rs.getString(1));
	System.out.print(",");
	System.out.print(rs.getString(2));
	System.out.print("\n");
	}
	rs.close();
	st.close();
	con.close();	
	//以上3个对象不要忘记close!
	}
	//后面两个异常处理
	catch (ClassNotFoundException e)
	{
	System.err.println("Can not load driver\n");
	System.exit(1);
	}
	catch (SQLException e)
	{
	System.err.println("Can not connect\n");
	System.exit(1);
	}
	//如果出现下面一行提示,则表示程序没有能够正常运行	
	System.out.println("Connection Is OK!");		
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?