Java connects to MySQL through JDBC to read data Learning notes

Source: Internet
Author: User

Code

The code is as follows: Copy code

Import java. SQL. Connection;
Import java. SQL. DriverManager;
Import java. SQL. Statement;
Import java. SQL. ResultSet;

Public class MyTest {
Public static void main (String args []) {
Connection con = null;
Try {
// Obtain the MySQL-driven instance
Class. forName ("com. mysql. jdbc. Driver"). newInstance ();
// Provide the address username and password and obtain the connection object
Con = DriverManager. getConnection ("jdbc: mysql: // 127.0.0.1/test", "root", "123456 ");
       
If (! Con. isClosed ())
// Connection success prompt
System. out. println ("Successfully connected to MySQL server using TCP/IP ...");
// Create a Statement with a Connection object
Statement st = con. createStatement ();
// Run the SQL statement to read
ResultSet rs = st.exe cuteQuery ("SELECT * FROM emlog_blog ");
// Read data cyclically
While (rs. next ()){
// Print data
System. out. println (rs. getString ("gid "));
            }
// Close
Con. close ();
} Catch (Exception e ){
System. err. println ("Exception:" + e. getMessage ());
        }
    }
}

Note that

The com. mysql. jdbc. Package needs to be downloaded from MySQL.

Download address:

Http://dev.mysql.com/downloads/connector/j/


After downloading the package, add the package to the libary of Eclipse to run the code above.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.