Steps for connecting to a MySQL database using Java

Source: Internet
Author: User

Step 1: Download a JDBC driver package, for example I'm using: mysql-connector-java-5.1.17-bin.jar (resources have been uploaded to my blog)

Step 2: import the downloaded JDBC driver package. I use myeclipse, select the project for which you want to export the package, right-click and select propertise, and then select javabuild path. libreries will appear on the right, click in, add external jars, and then find the driver package you want to import. Click order andexport, and then select the package you imported.

Step 3: load the driver: class. forname ("com. MySQL. JDBC. Driver ");

Step 4: connect to the database: Connection conn = drivermanager. getconnection ("JDBC: mysql: // localhost/Database Name", "root", "123456 ");

Step 5: declare a statement to execute the SQL statement: Statement stmt = conn. createstatement ();

Step 6: declare a result set to access the data that executes the SQL statement: resultset rs1_stmt.exe cutequery ("select * from table name ");

 

 

The complete code is provided below:

Try {class. forname ("com. mySQL. JDBC. driver "); system. out. println ("tested"); connection conn = drivermanager. getconnection ("JDBC: mysql: // localhost/myschool", "root", "123456"); system. out. println ("conn -------------" + conn); statement stmt = Conn. createstatement (); resultset rs1_stmt.exe cutequery ("select * from admin"); While (RS. next () {string name = Rs. getstring ("name"); string Pwd = Rs. getstring ("PWDs"); system. out. println ("name ------" + name + "-------- PWD-" + PWD);} catch (classnotfoundexception e) {// todo auto-generated Catch Block E. printstacktrace ();} catch (sqlexception e) {// todo auto-generated Catch Block E. printstacktrace ();}

 

 

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.