Java connection MySQL Database method detailed

Source: Internet
Author: User
Tags stmt mysql database

JDBC Connection MySQL Database

First download connector/j address: http://www.mysql.com/downloads/connector/j/
This is the official MySQL provided connection mode:
Extract the jar library file after decompression, you need to import the library file in the project
I'm using eclipse:

Java connection MySQL is a bit cumbersome, so write a class to open or close the database first:

The code is as follows Copy Code

Dbhelper.java


Package Com.hu.demo;

Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import java.sql.SQLException;

public class DBHelper {
public static final String URL = "Jdbc:mysql://127.0.0.1/student";
public static final String name = "Com.mysql.jdbc.Driver";
public static final String user = "root";
public static final String password = "root";

public Connection conn = null;
public PreparedStatement PST = NULL;

Public dbhelper (String sql) {
try {
Class.forName (name);//Specify connection type
conn = drivermanager.getconnection (URL, user, password);//Get connection
PST = conn.preparestatement (SQL);//ready to execute statement
catch (Exception e) {
E.printstacktrace ();
}
}

public void Close () {
try {
This.conn.close ();
This.pst.close ();
catch (SQLException e) {
E.printstacktrace ();
}
}
}

Write a demo.java to perform the related query operation

The code is as follows Copy Code

Package Com.hu.demo;

Import Java.sql.ResultSet;
Import java.sql.SQLException;

public class Demo {

static String sql = NULL;
static DBHelper db1 = null;
static RESULTSET ret = NULL;

public static void Main (string[] args) {
sql = "Select *from stuinfo";//sql statement
DB1 = new DBHelper (SQL);//Create DBHelper Object

try {
ret = Db1.pst.executeQuery ()//EXECUTE statement, get result set
while (Ret.next ()) {
String uid = ret.getstring (1);
String ufname = ret.getstring (2);
String ulname = ret.getstring (3);
String udate = ret.getstring (4);
SYSTEM.OUT.PRINTLN (uid + "\ T" + Ufname + "\ T" + Ulname + "T" + udate);
}//Display Data
Ret.close ();
Db1.close ()//close connection
catch (SQLException e) {
E.printstacktrace ();
}
}

}

The test database was created in the previous chapter, so direct query:

Example Two, Java connection MySQL database class file

The code is as follows Copy Code

Package sns.team6.util;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import java.sql.SQLException;

/**
* Link the Database tool class
*
* @author Xu Rui
*
*/
public class DBHelper {

MySQL Drive path
Private static final String Driver = "Com.mysql.jdbc.Driver";
Connection path for database
Private static final String URL = "JDBC:MYSQL://LOCALHOST:3306/SNSTEAM6";

/**
* Objects that connect to the database
*
* @return
*/
public static Connection getconnection () {
Connection conn = null;
try {
Class.forName (driver);
conn = drivermanager.getconnection (URL, "root", "root");
catch (Exception e) {
E.printstacktrace ();
}
Return conn;
}

/**
* Close the Open resource
*
* @param Conn
* @param PST
* @param rst
*/
public static void Closeinfo (Connection conn, PreparedStatement PST,
ResultSet rst) {
try {
if (rst!= null) {
Rst.close ();
rst = null;
}
if (PST!= null) {
Pst.close ();
PST = NULL;
}
IF (conn!= null) {
Conn.close ();
conn = null;
}
catch (Exception e) {
E.printstacktrace ();
}
}

/**
* Get result set object
*
* @param sql
* @param params
* @return
*/
public static ResultSet ResultSet (String sql, object[] params) {

The linked object of the database
Connection conn = null;
The Operation object of the database
PreparedStatement PST = NULL;
Result Object
ResultSet rst = null;
try {

The linked object of the database
conn = Dbhelper.getconnection ();
The Operation object of the database
PST = conn.preparestatement (SQL);
Determine if there are parameters
if (params!= null && params.length > 0) {
for (int i = 0; i < params.length; i++) {
Assigning a value to an Action object
Pst.setobject (i + 1, params[i]);
}
}
Get the result object
rst = Pst.executequery ();
catch (SQLException e) {
rst = null;
E.printstacktrace ();
}
return rst;
}

/**
* Get the added result object
*
* @param sql
* @param params
* @return
*/
public static Boolean result (String sql, object[] params) {

Boolean flag = false;
The linked object of the database
Connection conn = null;
The Operation object of the database
PreparedStatement PST = NULL;
try {
The linked object of the database
conn = Dbhelper.getconnection ();
The Operation object of the database
PST = conn.preparestatement (SQL);
Determine if there are parameters
if (params!= null && params.length > 0) {
for (int i = 0; i < params.length; i++) {
Assigning a value to an Action object
Pst.setobject (i + 1, params[i]);
}
}
Gets the result object, which is the int type, indicating the number of rows executed successfully
int row = Pst.executeupdate ();
if (Row > 0) {
If greater than 0 indicates successful execution
Flag = true;
}
catch (SQLException e) {
Flag = false;
E.printstacktrace ();
}
return flag;
}
}

Example

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


public class Mysqldemo {
public static void Main (string[] args) throws Exception {
Connection conn = null;
String SQL;
MySQL jdbc URL write way: jdbc:mysql://host Name: Connection port/database name? parameter = value
Avoid Chinese garbled to specify Useunicode and characterencoding
To create a database on the database management system before performing the database operation, the name is set by itself.
The following statement must first create the Javademo database
String url = "Jdbc:mysql://localhost:3306/javademo?"
+ "User=root&password=root&useunicode=true&characterencoding=utf8";

try {
The reason to use the following statement is to use the MySQL driver, so we're going to drive it,
It can be loaded through class.forname, or it can be driven by initialization, and the following three forms can be
Class.forName ("Com.mysql.jdbc.Driver")//dynamic load MySQL Driver
Or
Com.mysql.jdbc.Driver Driver = new Com.mysql.jdbc.Driver ();
Or
New Com.mysql.jdbc.Driver ();

System.out.println ("Successfully loaded MySQL driver");
A connection represents a database connection
conn = drivermanager.getconnection (URL);
Statement contains many methods, such as executeupdate can be inserted, updated and deleted, etc.
Statement stmt = Conn.createstatement ();
sql = "CREATE TABLE student (no char (), name varchar (), primary key (No))";
int result = stmt.executeupdate (SQL);//Executeupdate statement returns an affected number of rows, if return-1 is not successful
If (Result!=-1) {
SYSTEM.OUT.PRINTLN ("Create data table succeeded");
sql = "INSERT into student (No,name) VALUES (' 2012001 ', ' Tao Weiki ')";
result = Stmt.executeupdate (SQL);
sql = "INSERT into student (No,name) VALUES (' 2012002 ', ' Zhou Xiaojun ')";
result = Stmt.executeupdate (SQL);
sql = "SELECT * from student";
ResultSet rs = stmt.executequery (sql);//ExecuteQuery Returns a collection of results, otherwise null values are returned
System.out.println ("School number \ t name");
while (Rs.next ()) {
System.out
. println (rs.getstring (1) + "T" + rs.getstring (2));/Enter if the type of int returned can be getint ()
}
}
catch (SQLException e) {
System.out.println ("MySQL operation Error");
E.printstacktrace ();
catch (Exception e) {
E.printstacktrace ();
finally {
Conn.close ();
}

}

}

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.