Java Connection MySQL Database

Source: Internet
Author: User

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

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.