Working directory:
Right-click the project, select Build path, select Configure build Path, and add the jar package in the Lib directory to the path.
Program code:
Package Com.test;import java.sql.*;//introduces the pack public class Mysqlconntest {public mysqlconntest () {status =-1; SetConnection (NULL); try {Class. forname ("Com.mysql.jdbc.Driver");//Load Driver SetConnection (DriverManager. Getconne Ction ("Jdbc:mysql://localhost:3306/test", "root", "123456")); Establish connection} catch (Exception e) {e.printstacktrace (); } status = 1; } public static void Main (String args[]) throws sqlexception{mysqlconntest instance = new Mysqlconnte St (); if (instance.getstatus () = = 1) {//Status Ready instance. Testwrite (); Instance. Testread (); Instance.getconnection (). Close (); }}//test writer public void Testwrite () throws sqlexception{preparedstatement statement = Getcon Nection (). Preparestatement ("INSERT into test (name) values (' HEllo ') "); Statement.executeupdate (); }//test read program public void Testread () throws sqlexception{preparedstatement statement = getconnection (). Preparestatement ("SELECT * from Test"); ResultSet result = Statement.executequery (); while (Result.next ()) {System. OUT.PRINTLN ("id =" + result.getint (1) + ", name =" + result. GetString (2)); } result.close (); } private int status; Private Connection Connection; public int GetStatus () {return status; public void setStatus (int status) {this. status = Status; } public Connection getconnection () {return Connection; } public void SetConnection (Connection Connection) {this. Connection = Connection; }}
SQL file:
CREATE DATABASE IF not EXISTS ' test '; Use ' Test ';D rop TABLE IF EXISTS ' test '; CREATE TABLE ' test ' ( ' id ' int (one) not null auto_increment, ' name ' varchar) DEFAULT NULL, PRIMARY KEY (' id ') )) Engine=innodb auto_increment=5 DEFAULT Charset=utf8;
Operation Result:
The END
Eclipse connection to MySQL database