Java connection MySQL database and simple operation code

Source: Internet
Author: User
Tags psql

1.Java connecting MySQL Database

Java connection MySQL needs to download the JDBC driver Mysql-connector-java-5.0.5.zip (for example, the existing new version). Then unzip it to either directory. I was extracted to the D drive, and then add the Mysql-connector-java-5.0.5-bin.jar in its directory to Classpath, as follows:

"My Computer", "Properties", "Advanced", "Environment variable", edit classpath in the system variable, will D:\MySQL-connector-java-5.0.5\ Mysql-connector-java-5.0.5-bin.jar to the end, add ";" before adding the string to separate from the previous Classpath area. And then determine.


Package Hqs;import java.sql.*;p ublic class Databasepractice {public static void main (string[] args) {// Declares the Connection object connection con;//driver name string driver = "Com.mysql.jdbc.Driver";//url points to the database name to access mydatastring URL = "JDBC: Mysql://localhost:3306/mydata ";//mysql username String user =" root ",//mysql configuration password string password =" root ";//Traverse query result set try {//Load driver Class.forName (driver);//1.getconnection () method, connect MySQL database!! con = drivermanager.getconnection (Url,user,password), if (!con.isclosed ()) System.out.println ("succeeded connecting To the database! "); /2. Create a statement class object to execute the SQL statement!! Statement Statement = Con.createstatement ();//SQL statement to execute string sql = "SELECT * from Student";//3.resultset class, used to hold the result set obtained!! ResultSet rs = statement.executequery (SQL); System.out.println ("-----------------");  System.out.println ("Execution results are as follows:");  System.out.println ("-----------------");  System.out.println ("School number" + "\ T" + "name");  System.out.println ("-----------------"); String name = NULL; String id = null;while (rs.next ()) {//Get stuname This column of data name = Rs.getstring ("Stuname");//Get STUID this column data id = rs.getstring ("Stuid");//First Use the iso-8859-1 character set to decode name into a sequence of bytes and store the result in a new byte array. The specified byte array is then decoded using the GB2312 character set. name = new String (name.getbytes ("iso-8859-1"), "gb2312");//output result System.out.println (id + "\ T" + name);}Rs.close (); Con.close ();}   catch (ClassNotFoundException e) {//database-driven class exception handling System.out.println ("Sorry,can ' t find the driver!");   E.printstacktrace ();  } catch (SQLException e) {//database connection failed exception handling E.printstacktrace (); }catch (Exception e) {//Todo:handle exceptione.printstacktrace ();} FINALLY{SYSTEM.OUT.PRINTLN ("Database data successfully obtained!! ");}}}
2. Add, modify, delete the following code snippet is added after the while code snippet above:
String name = NULL; String id = null;while (rs.next ()) {//Gets stuname This column of data name = Rs.getstring ("Stuname");//Get STUID this column data id = rs.getstring ("Stuid ");//First Use the iso-8859-1 character set to decode name into a sequence of bytes and store the result in a new byte array. The specified byte array is then decoded using the GB2312 character set. name = new String (name.getbytes ("iso-8859-1"), "gb2312");//output result System.out.println (id + "\ T" + name);} PreparedStatement Psql; ResultSet res;//preprocessing adds data with two parameters--"? "Psql = Con.preparestatement (" INSERT into student values (?,?) "); Psql.setint (1, 8); Set parameter 1, create data with ID 5 psql.setstring (2, "Xiaogang");//Set parameter 2,name for Xiaoming psql.executeupdate ();//Perform update//preprocessing update (modify) Data Psql = Con.preparestatement ("update student set stuname =?") where Stuid =? "); Psql.setstring (1, "Xiaowang");//Set parameter 1, change name to Harry Psql.setint (2,10),//Set parameter 2, change the data with ID 2 to psql.executeupdate ();// preprocessing deletes data Psql = con.preparestatement ("Delete from student where Stuid =?"); Psql.setint (1, 5);p sql.executeupdate ();//The data in the Student table after query modification data Psql = con.preparestatement ("select*from student"); res = Psql.executequery ();//execute preprocessing SQL statement System.out.println ("Execute Add, modify, delete data"); whiLe (Res.next ()) {name = Res.getstring ("Stuname"); id = res.getstring ("Stuid"); name = new String (Name.getbytes (" Iso-8859-1 ")," gb2312 "); System.out.println (id + "\ T" + name);} Res.close ();p sql.close ();

The code snippet uses a preprocessing statement:
Con.preparestatement (String sql);
This builds the underlying internal command of the database and encapsulates the command in the PreparedStatement object, reducing the burden on the database and increasing the speed of access to the database. Operation Result:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.