Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to connect to database in JDBC

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report