Get the App
SLTechnology News&Howtos  ›  Database  › 

How to connect to database in JDBC

Shulou Source: shulou.com Published: 2022-05-31 13:49:59 10月04日 Update

This article mainly shows you "how to connect to the database in JDBC", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to connect to the database in JDBC" this article.

To connect to a database:

Register driver

Establish a connection (Connection)

Create a statement that executes SQL (Statement)

Execute statement

Processing execution result (ResultSet)

Release resources

Static void test () throws SQLException, ClassNotFoundException {/ 1. Register driver, all three, use frequency 3 > 1 > 2 DriverManager.registerDriver (new com.mysql.jdbc.Driver ()); System.setProperty ("jdbc.drivers", "com.mysql.jdbc.Driver"); Class.forName ("com.mysql.jdbc.Driver"); / / 2. Establish a connection, URL format: JDBC: subprotocol: subname / / hostname: Port / database name? Attribute name = attribute value &. String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "timewalkfv"; Connection conn = DriverManager.getConnection (url,user,password); / / 3. Create the statement Statement st = conn.createStatement (); / / 4. Execute the statement ResultSet rs = st.executeQuery ("select * from user"); / / 5. Processing result while (rs.next ()) {System.out.println ("id:" + rs.getObject (1) + "\ t name:" + rs.getObject (2) + "\ t birthday:" + rs.getObject (3));} / / 6. Release resources. Database connection (Connection) is a very rare resource, which must be released immediately after use. / / if Connection is not shut down correctly in time, it will lead to system downtime. The principle for using Connection is to create it as late as possible and release it as early as possible. Rs.close (); st.close (); conn.close (); / /} these are all the contents of the article "how to connect to a database in JDBC". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Data databases statements content articles resources attributes results processing learning help drivers rarity hosts principles names understandable more organized formatted Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi macOS Redmi Shulou Technology Linux