ImportJava.sql.DriverManager;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Connection;Importjava.sql.Statement; Public classMysqldemo { Public Static voidMain (string[] args)throwsException {Connection conn=NULL; String SQL; //mysql jdbc url writing method: Jdbc:mysql://Host Name: Name of the connection port/database? parameter = value//avoid Chinese garbled to specify Useunicode and characterencoding//to create a database on a database management system before performing a database operation, the name will be//The following statement is preceded by the creation of the Javademo databaseString url = "Jdbc:mysql://localhost:3306/javademo?" + "User=root&password=root&useunicode=true&characterencoding=utf8"; Try { //The reason to use the following statement is because you want to use the MySQL driver, so we have to drive it up,//it can be loaded through class.forname, or it can be driven by initialization, and the following three forms can beClass.forName ("Com.mysql.jdbc.Driver");//dynamic load MySQL driver//or://com.mysql.jdbc.Driver Driver = new Com.mysql.jdbc.Driver (); //or://new Com.mysql.jdbc.Driver ();System.out.println ("Load MySQL driver successfully"); //a connection represents a database connectionconn =drivermanager.getconnection (URL); //statement contains many methods, such as executeupdate can be inserted, update and delete, etc.Statement stmt =conn.createstatement (); SQL= "CREATE table student (no char (), name varchar (), primary key (NO))"; intresult = Stmt.executeupdate (SQL);//The Executeupdate statement returns an affected number of rows if the return-1 is not successful if(Result! =-1) {System.out.println ("Create data Table succeeded"); SQL= "INSERT into student (No,name) VALUES (' 2012001 ', ' Tao Weiki ')"; Result=stmt.executeupdate (SQL); SQL= "INSERT into student (No,name) VALUES (' 2012002 ', ' Zhou Xiaojun ')"; Result=stmt.executeupdate (SQL); SQL= "SELECT * FROM Student"; ResultSet RS= Stmt.executequery (SQL);//ExecuteQuery Returns a collection of results, otherwise a null value is returnedSystem.out.println ("School number \ t name")); while(Rs.next ()) {System.out. println (rs.getstring (1) + "\ T" + rs.getstring (2));//if the type int is returned can be used Getint () } } } Catch(SQLException e) {System.out.println ("MySQL Operation Error"); E.printstacktrace (); } Catch(Exception e) {e.printstacktrace (); } finally{conn.close (); } } }
Methods and examples of JDBC connection to MySQL database