Java connects MySQL database with JDBC

Source: Internet
Author: User

First step: Download mysql driver, url

http://dev.mysql.com/downloads/connector/j/

Step two: Talk about MySQL driver mysql-connector-java-5.0.5-bin.jar Add to the project's Lib directory or add the path of the file to the CLASSPATH environment variable

Step three: Build a database

1. Install MySQL

2, the establishment of the database: create databases test;

3. Create a table:

CREATE TABLE STUDENT (SNO char (7) NOT NULL, SNAME VARCHAR (8) is not NULL, SEX CHAR (2) is not NULL, bdate DATE is not NULL, H EIGHT DEC (5,2) DEFAULT 000.00, PRIMARY KEY (SNO));

4. Inserting data

Fourth Step: Java program writing

1. Load driver: Load the driver of the database you want to connect to the JVM, implemented by the static method forname (String className) of the Java.lang.Class class, and after the load is successful, Instances of the driver class are registered in the DriverManager

Class.forName ("Com.mysql.jdbc.Driver"). newinstance (); or com.mysql.jdbc.Driver Driver = new Com.mysql.jdbc.Driver (); or new Com.mysql.jdbc.Driver ();

2. Create a Connection object, which is a database connection

connection con = drivermanager.getconnection ("url",  "user",  "Passwrod"); 

Where MySQL's jdbc URL is written: jdbc:mysql:// Host Name: Connection port/database name? parameter = value, avoid Chinese garbled to specify Useunicode and characterencoding.

3, create a declaration: Create a java.sql.Statement instance, statement instances are divided into the following three types:

1 , execute a static SQL statement.     Typically implemented through statement instances.

2 , execute dynamic SQL statements.     Typically implemented through PreparedStatement instances.

3 , execute the database stored procedure.     Typically implemented through CallableStatement instances.

the specific implementation method:

Statement stmt = Con.createstatement ();
PreparedStatement pstmt = con.preparestatement (sql);
CallableStatement cstmt = Con.preparecall ("{Call Demosp (?,?)}");

4. Perform database operations: The statement interface provides three ways to execute SQL statements: ExecuteQuery, Executeupdate, and execute.

     1 ResultSet  executequery (): Executes the SQL statement that queries the database, and returns a result set (ResultSet) object.       2 int  executeupdate (): Used to perform INSERT, update, or DELETE statements and SQL DDL statements, such as: Create table and drop table,     

3.execute (): Used to perform statements that return multiple result sets, multiple update counts, or combinations of both.

Specific implementation code:

5. Processing result: Two kinds of situation

1 , the number of records affected by this operation returned by performing the update

2 . The result of executing the query returned is a ResultSet object

resultset contains all rows that conform to the conditions in the SQL statement, and it provides access to the data in those rows through a set of Get methods.

Get data using the access method of the result set (ResultSet) object:

while (Rs.next ()) {

String name = rs.getstring ("name");

String pass = rs.getstring (1);

}

6. Close the JDBC object: After the operation is complete, all the JDBC objects used are closed to release the JDBC resource, and the order of closing and declaration is reversed:

1 , close the recordset

2 , close the statement

3 , close the Connection object


Here is the test code for Learning:

package com.nudt.jdbc;import java.net.connectexception;import java.sql.*;p Ublic class  DBUtilDemo{    private static final String URL =  "jdbc : Mysql://127.0.0.1:3306/imooc ";     private static final string user  =  "root";    private static final string passwd=  " nudt2013 ";    private static connection conn = null;     static {        try {             class.forname ("Com.mysql.jdbc.Driver");             conn = drivermanager.getconnection (URL,USER, PASSWD);        } catch  (classnotfoundexception e)  {     &Nbsp;      e.printstacktrace ();         }  catch  (sqlexception e)  {             e.printstacktrace ();         }    }     public static connection getconnection () {         return conn;    }    public static  void main  (string args[]) throws exception{         Statement stmt = conn.createstatement ();         Resultset rs = stmt.executequery ("select user_name,age from imooc_goddess");         String result = null;         while (RS.NExt ()) {            result =  "Name:" + Rs.getstring ("user_name") + "; Age:" +rs.getint ("Age");             SYSTEM.OUT.PRINTLN (Result);        }     }}


Java connects MySQL database with JDBC

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.