A classic JDBC connection to MySQL program

Source: Internet
Author: User

Import java.sql.Connection;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import java.sql.Statement;
public class Mysqlconnection {
public static void Main (string[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String URL = null;
String user = null;
String password = null;
String sql = null;
try {
Class.forName ("Com.mysql.jdbc.Driver"); Load MYSQ Driver
} catch (ClassNotFoundException e) {
SYSTEM.OUT.PRINTLN ("Driver loading error");
E.printstacktrace ();//Print Error details
} try {
URL =
"Jdbc:mysql://localhost/test?user=root&password=yqs2602555&useunicode=true&&characterencoding= Gb2312&autoreconnect = true ";//simple notation: url =" jdbc:myqsl://localhost/test (database name)?   User=root (user) &password=yqs2602555 (password) "; user = "Root";
Password = "yqs2602555";
conn = Drivermanager.getconnection (Url,user,password);
} catch (SQLException e) {
SYSTEM.OUT.PRINTLN ("Database link error");
E.printstacktrace ();
}
try {
stmt = Conn.createstatement ();
sql = "SELECT * from dept";//dept This table has three fields of deptno,deptname and age
rs = stmt.executequery (sql);//Execute SQL statement
while (Rs.next ()) {
System.out.print (Rs.getint ("deptno") + "");
System.out.print (rs.getstring ("deptname") + "");
System.out.println (Rs.getint ("age") + "");
}
} catch (SQLException e) {
SYSTEM.OUT.PRINTLN ("Data manipulation error");
E.printstacktrace ();
}//shutting down the database
try {
if (rs! = null) {
Rs.close ();
rs = null;
}
if (stmt! = null) {
Stmt.close ();
stmt = null;
}
IF (conn! = null) {
Conn.close ();
conn = null;
}
} catch (Exception e) {
SYSTEM.OUT.PRINTLN ("Database shutdown error");
E.printstacktrace ();
}
}
The results of the operation are as follows: 1 Yqs 0
2 Hello 0
3 Yqsshr 0
4 World 0
5 Hryspa 0
1 Yqs 0
2 Hello 0
3 Yqsshr 0
4 World 0
5 Hryspa 0
1 YQS11 21
1 YQS21 31
1 YQS31 41
1 YQS41 51

A classic JDBC connection to MySQL program

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.