Java JDBC Link Database

Source: Internet
Author: User

1. Registration Driver
Class.forName ("Com.mysql.jdbc.Driver");//This is the driver that connects the MySQL database
2. Get a database connection
Java.sql.Connection conn=java.sql.drivermanager.getconnection (); 3. Get an expression
Java.sql.Statement stmt=conn.createstatement ("jdbc:mysql://localhost/test?useunicode=true&characterencoding =gbk "," root "," null ");//Three parameters are the URL of the database connection, user name, password 4. Execute SQL
Java.sql.ResultSet rs=stmt.executequery ("SELECT * from user"); 5. Display the data in the result set
while (Rs.next ()) {
System.out.println (Rs.getint (1));
System.out.println (rs.getstring ("username"));
System.out.println (rs.getstring ("password"));
System.out.pringln ();
}//executing an INSERT statement
Stmt.executeupdate ("INSERT into user values (1, ' Chinese ', ' 345 ')");
6. Releasing Resources
Rs.close ();
Stmt.close ();
Conn.close (); Package COM.JIKEXUEYUAN.JDBC;

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



public class Jdbctest {
public static void Main (string[] args) {
String sql= "SELECT * from Tbl_user";
Connection Conn=null;
Statement St=null;
ResultSet Rs=null;
try {
Class.forName ("Com.mysql.jdbc.Driver");
Conn=drivermanager.getconnection ("jdbc:mysql://localhost:3306/jsp_db", "Root", "" ");

St=conn.createstatement ();
Rs=st.executequery (SQL);
while (Rs.next ()) {
System.out.print (Rs.getint ("id") + "");
System.out.print (rs.getstring ("name") + "");
System.out.print (rs.getstring ("password") + "");
System.out.print (rs.getstring ("email") + "");
System.out.println ();
}
} catch (Exception e) {
E.printstacktrace ();
}finally {
try {
Rs.close ();
St.close ();
Conn.close ();
} catch (Exception E2) {
E2.printstacktrace ();
}
}
}

}

Java JDBC Link Database

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.