/************************************************************************* > File Name:Mysql.java > Author: Baiyan > Test Instructions: > Created time:2016 June 04 Saturday 01:03 32 sec. ********************************************************** ************/Import Java.sql.drivermanager;import Java.sql.resultset;import java.sql.sqlexception;import Com.mysql.jdbc.connection;import java.sql.Statement; Public classmysql{ Public Static voidMain (string[] args) throws Exception {Connection conn=NULL; String URL="jdbc:mysql://localhost:3306/sample?"+"User=root&password=www1964878036&useunicode=true&characterencoding=utf-8"; //load the MySQL driver class first; Try{class.forname ("Com.mysql.jdbc.Driver"); System. out. println ("Drive loaded successfully! "); Conn=(Connection) drivermanager.getconnection (URL); //Connection represents a link to a database;// //The Java.sql.Statement instance must be obtained to execute the SQL statement;Statement stmt =conn.createstatement (); //Statement instances have the following three types://execute static SQL statements, implemented by statement instances;//Execute Dynamic SQL statements, implemented by PreparedStatement instances;//execute the database stored procedure, usually through CallableStatement instance implementation;//The above is one of them, the other two are given below;// //PreparedStatement pstmt = conn.preparesstatement (sql); //callablestatement cstmt = Con.preparecall ("{Call DEMOSP (?,?)}") ;// //then execute the SQL statement;//There are three ways to execute SQL statements//executeQuery, executeupdate, execute// //talk about the use of the threeString sql="CREATE TABLE student (id char, name char, primary key (ID))"; intresult = Stmt.executeupdate (SQL);//returns the number of rows affected;//return-1 means no success;ResultSet rs =NULL; if(Result! =-1) {SQL="INSERT into student (Id,name) VALUES (' 1234 ', ' Biayan ')"; Result=stmt.executeupdate (SQL); SQL="SELECT * FROM Student"; RS=stmt.executequery (SQL); //This sentence returns the result set; while(Rs.next ()) {System. out. println (Rs.getstring (1)+"\ t"+rs.getstring (2)); } } //as you can see, query is used to process queries;//Update for INSERT, UPDATE, delete, Drop;//the other statement used for composition;//for the result set, you can also use GetString ("name") to live content;//the columns are numbered starting from 1;// // //then you want to close the connection; if(rs!=NULL)//close the recordset;{Try{rs.close (); }Catch(SQLException e) {e.printstacktrace (); } } if(stmt! =NULL)//closing the declaration; { Try{stmt.close (); }Catch(SQLException e) {e.printstacktrace (); } } if(conn!=NULL) { Try{conn.close (); }Catch(SQLException e) {e.printstacktrace (); } } }Catch(ClassNotFoundException e) {System. out. println ("driver class not found, load driver failed"); E.printstacktrace (); } //when the load succeeds, the instance of MySQL's driver class is registered to the Drivermanger class; }}
Java Link Database--mysql