1 Packagecom.tn.mysqlconnection;2 3 Importjava.sql.Connection;4 ImportJava.sql.DriverManager;5 Importjava.sql.PreparedStatement;6 ImportJava.sql.ResultSet;7 Importjava.sql.SQLException;8 9 Public classmysqlconnection {Ten Private Static FinalString dbdriver = "Com.mysql.jdbc.Driver"; One Private Static FinalString Dburl = "jdbc:mysql://localhost:3306/" A+ "[Email protected][email Protected]=true&characterencoding=utf8"; - Private Static FinalString URL = "Jdbc:mysql://localhost:3306/db_tuniu"; - Private Static FinalString DBUSER = "Xiongjiawei"; the Private Static FinalString PASSWORD = "Tuniu520"; - PrivateConnection conn =NULL; - - Publicmysqlconnection () { + Try { - Class.forName (dbdriver); + This. conn =drivermanager.getconnection (URL, DBUSER, PASSWORD); A}Catch(Exception e) { at e.printstacktrace (); - } - } - - PublicConnection getconnection () { - return This. Conn; in } - to Public voidClose () { + if( This. conn! =NULL) { - Try { the This. Conn.close (); *}Catch(SQLException e) { $ e.printstacktrace ();Panax Notoginseng } - } the } + A Public Static voidMain (string[] args) { theMysqlconnection mysqlconnection =Newmysqlconnection (); +Connection conn =mysqlconnection.getconnection (); -String sql = "INSERT into student (name) VALUES (?)"; $ Try { $PreparedStatement statement =conn.preparestatement (SQL); - //ResultSet resultset=statement.executequery (); -Statement.setstring (1, "Shoko"); the System.out.println (Statement.executeupdate ()); - conn.close ();Wuyi}Catch(SQLException e) { the e.printstacktrace (); - } Wu } -}View Code
"Java" JDBC connection MySQL