1. First create a Java project Testmysql (I'm using the IntelliJ editor).
2. Import the MySQL driver package.
(1)
(2)
(4)
3. Writing code
Import Java.sql.Connection;
Import Java.sql.DriverManager;
Import Java.sql.SQLException;
/**
* Created by Wuy on 2015/7/24.
*/
public class Testmysql {
Private ConnectionCon;
Private StringUser="Root";
Private Stringpassword="Root";
Private StringClassname="Com.mysql.jdbc.Driver";
Private StringURL ="Jdbc:mysql://127.0.0.1:3306/goods";
Public Testmysql () {
try{
Class.Forname (ClassName);
System.Out.println ("Load Database driver succeeded!" ");
}catch (ClassNotFoundException e) {
System.Out.println ("Load Database driver failed!" ");
E.printstacktrace ();
}
}
/** Creating a database connection */
Public ConnectionGetcon () {
try {
Con= DriverManager.Getconnection (wr.,User,Password;
System.Out.println ("CREATE DATABASE connection succeeded!" ");
}catch (SQLException e) {
System.Out.print (Con;
System.Out.println ("Failed to create database connection!" ");
con=Null
E.printstacktrace ();
}
ReturnCon;
}
public voidClosed () {
try{
Ifcon!=NULL) {
con.close ()
}catch (SQLException e) {
System.out.println ( "Closing Con object failed! ") ;
E.printstacktrace () }
}
public static void main (string[] args)
{
Testmysql c=new Testmysql () C.getcon () c.closed () ;
}
/span> 4. Run result
< Span style= "color: #cc7832;" >< Span style= "color: #6a8759;" >< Span style= "color: #cc7832;" > /span>
Java connection to MySQL database