1 PackageTommypackage;2 3 Importjava.sql.Connection;4 ImportJava.sql.DriverManager;5 Importjava.sql.PreparedStatement;6 Importjava.sql.SQLException;7 8 Public classMyTest {9 Ten Private StaticConnection Getconn () { OneString Driver = "Com.mysql.jdbc.Driver"; AString url = "JDBC:MYSQL://SH-CDB-KLJDEOIS.SQL.TENCENTCDB.COM:63014/YXM"; -String username = "root"; -String password = "J3s4d5f6"; theConnection conn =NULL; - Try { -Class.forName (driver);//classLoader, load the corresponding drive -conn =drivermanager.getconnection (URL, username, password); +}Catch(ClassNotFoundException e) { - e.printstacktrace (); +}Catch(SQLException e) { A e.printstacktrace (); at } - returnConn; - } - - Public Static voidMain (string[] args)throwsClassNotFoundException, SQLException { -Connection con =getconn (); inPerson PS =NewPerson (); - toPs.setlastname ("Tommy"); +Ps.setfirstname ("Lorry"); -Ps.setaddress ("Telecom Building"); thePs.setcity ("Shanghai"); * $StringBuilder SB =NewStringBuilder ();Panax NotoginsengSb.append ("\ '" + ps.getlastname () + "\" "); -Sb.append (","); theSb.append ("\ '" + ps.getfirstname () + "\" "); +Sb.append (","); ASb.append ("\ '" + ps.getaddress () + "\" "); theSb.append (","); +Sb.append ("\ '" + ps.getcity () + "\" "); - $ if(Con! =NULL) { $SYSTEM.OUT.PRINTLN ("MySQL connection succeeded! "); - - //Insert theString s = "+" INSERT into Persons (lastname,firstname,address,city) VALUES ("+ sb.tostring () +") "; -PreparedStatement Pst1 =Con.preparestatement (s);Wuyi if(Pst1.execute ()) { theSystem.out.println ("Insert data successfully! "); -}Else { WuSystem.out.println ("Insert data failed! "); - } About $ //Delete -String t = "Delete from Persons where lastname= '" + ps.getlastname () + "'"; -PreparedStatement Pst2 =con.preparestatement (t); - inti = Pst2.executeupdate ();//I return the number of deleted records ASystem.out.println ("deleted:" + i + "bar data!) "); + the //Modify -String cityname = "London"; $String u = "Update Persons set lastname= '" + ps.getlastname () + "' Where city= '" + cityname + "'"; thePreparedStatement Pst3 =con.preparestatement (u); the intj = pst3.executeupdate ();//J Returns the number of records updated the theSystem.out.println ("Updated:" + j + "bar data!) "); - in //Close Resource the pst1.close (); the pst2.close (); About pst3.close (); the con.close (); the } the } +}
JDBC Additions and deletions change