1 Package Com.iwb.SimpleBBS.jdbc;2 3 import java.sql.Connection;4 import Java.sql.DriverManager;5 import Java.sql.ResultSet;6 import java.sql.SQLException;7 import java.sql.Statement;8 9 Public classjdbcoption {Ten Public Static voidMain (string[] args) throws exception{ OneConnection conn=NULL; A String SQL; - //mysql jdbc URL is written in the way: Jdbc:mysql://Host Name: Link port, database name? Parameter = value - //specify Useunicode and characterencoding as Utf-8 theString url="jdbc:mysql://localhost:3306/bbs_user?" -+"User=root&password=123456&useunicode=true&characterencoding=utf8"; - Try { - //loading the JDBC driver +Class.forName ("Com.mysql.jdbc.Driver"); -System. out. println ("successfully loaded MySQL driver"); + //a connection represents a database connection Aconn=drivermanager.getconnection (URL); at //statement There are many methods, Excuteupdate can implement insert delete update, etc. -Statement st=conn.createstatement (); -Sql="CREATE TABLE student (no char, name varchar, primary key (NO))"; - intResult=st.executeupdate (SQL);//Excuteupdate executes the SQL statement, returns the number of rows affected, and returns 1 indicating no success - if(result!=-1){ -System. out. println ("CREATE DATABASE succeeded"); inSql="INSERT into student (No,name) VALUES (' 2016001 ', ' Lili ')"; -result=st.executeupdate (SQL); toSql="INSERT into student (No,name) VALUES (' 2016002 ', ' Yangyang ')"; +result=st.executeupdate (SQL); -Sql="SELECT * FROM Student"; theResultSet rs=st.executequery (SQL);//Excutequery Returns the result set, otherwise returns a null value *System. out. println ("School number \ t name"); $ while(Rs.next ()) {Panax NotoginsengSystem. out. println (Rs.getstring (1)+"\ t"+rs.getstring (2));//if the int type can be used with the Getint () method - the } + } A}Catch(SQLException e) { theSystem. out. println ("MySQL operation error"); + //Todo:handle Exception - e.printstacktrace (); $}Catch(Exception e) { $ e.printstacktrace (); -}finally{ - conn.close (); the } - Wuyi } the}
JDBC Connection MySQL Database