Steps for JDBC Connection database (query)

Source: Internet
Author: User

Import the jar package first

Code:


Import java.sql.Connection;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import java.sql.Statement;

public class Firstjdbc {
public static void Main (string[] args) throws ClassNotFoundException, SQLException {

1) Register Load Driver
Class.forName ("Com.mysql.jdbc.Driver");
Drivermanager.registerdriver (New Com.mysql.jdbc.Driver ());
2) Get Connected
String url = "Jdbc:mysql://localhost:3307/mydb";//mydb is the name of the database
String user = "root"; Login name of the database
String password = "123456"; Login Password for database
Connection conn = drivermanager.getconnection (URL, user, password);
3) Create statement object
Statement st = Conn.createstatement ();
4) Execute SQL to get results
String sql = "SELECT * from EMP"; EMP is the name of the table to query
ResultSet rs= st.executequery (SQL);
5) Processing Results
while (Rs.next ()) {
System.out.print (Rs.getobject (1) + "\ T");
System.out.print (Rs.getobject (2) + "\ T");
System.out.print (Rs.getobject (3) + "\ T");
System.out.print (Rs.getobject (4) + "\ T");
System.out.print (Rs.getobject (5) + "\ T");
System.out.print (Rs.getobject (6) + "\ T"); Total output of field name information to display
}
6) Close Resources
Rs.close ();
St.close ();
Conn.close ();
}
}

Steps for JDBC Connection database (query)

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.