MySQL database connection and additions and deletions to change Java code implementation (PreparedStatement version)

Source: Internet
Author: User

Database:

CREATE TABLE t1 (ID int primary key NOT NULL Auto_increment,name varchar (+), password varchar); insert INTO T1 (name,pass Word) VALUES (' admin ', ' 123 '); INSERT into T1 (Name,password) VALUES (' Zhangsan ', ' 123 '); INSERT into T1 (Name,password) VALUES (' Lisi ', ' 123 ');

Java code:


Mysqlconnection.java Code:

Package Com.dbdao.mysql;import Java.sql.connection;import Java.sql.drivermanager;import java.sql.PreparedStatement ; Import Java.sql.resultset;import Java.sql.sqlexception;import Org.junit.test;public class Mysqlconnection {// Create database driver name private static string driver_class= "Com.mysql.jdbc.Driver";//Database link address private String url= "jdbc:mysql:// Localhost:3306/test ";//database user name private string user=" root ";//Database Password private string password=" 11 ";//Database link private Connection con=null;//prepare to declare SQL statement private PreparedStatement pstmt=null;//result set private ResultSet rs=null;//affect line number private int i;/* * Create driver * */static{try {class.forname (driver_class);} catch (ClassNotFoundException e) {//TODO auto-generated catch B Locke.printstacktrace ();}} /* * Load Driver * */@Testpublic void GetConnect () {//TODO auto-generated method stubtry {con=drivermanager.getconnection (URL, u SER, password);} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();} Determine if the database is loaded successfully if (con!=null) {System.out.println ("Database loaded successfully! ");} Else{system.out.pRINTLN ("Database load failed! ");}} /* * Execute SQL statement * */public void Dosql (String sql,object[] Object) {//TODO auto-generated method stub//determine if the SQL statement exists if (Sql!=nul L) {//Load drive getconnect ();//Determine if an object array exists if (object==null) {//If not present, create one to prevent null pointer exceptions object=new object[0];} try {//Declare a prepared SQL statement pstmt=con.preparestatement (SQL);//Assign a value of object one by one for (int i=0;i<object.length;i++) { Pstmt.setobject (i+1, Object[i]);} Execute declaration of SQL statement Pstmt.execute ();} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} ELSE{SYSTEM.OUT.PRINTLN ("SQL statement does not exist!") ");}} /* * Get result set * */public ResultSet getrs () {try {//Get result set method Rs=pstmt.getresultset ();} catch (SQLException e) {//TODO Auto-gener Ated catch Blocke.printstacktrace ();} Return result set return RS; /* * Gets the number of rows affected * */public int getupdatecount () {//TODO auto-generated method Stubtry {//Get Influence line number methods I=pstmt.getupdatecount ();} C Atch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();} Returns the number of rows affected return I;} /* * Close method * */public void Getclose () {//TODO auto-generated method stub//Close ResultSet try {//Result set Close method Rs.close ();} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally{//close declared SQL statement try {//close declaration of SQL statement Method Pstmt.close ();} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally{//Uninstall Drive try {//Drive Unload Method Con.close ();} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} }}}

Loginservice.java Code:

Package Com.service;import Java.sql.resultset;import Java.sql.sqlexception;import org.junit.test;import Com.dbdao.mysql.mysqlconnection;public class Loginservice {//import mysqlconnection classes Mysqlconnection mysqlCon=new Mysqlconnection ();//Prepare the SQL statement private String sql;//affect the number of rows (after the data change, affecting the number of rows is greater than 0, equal to 0 o'clock is not changed, so that if the change fails, then affect the number of rows must be negative) private int i=-1  ;//result set private ResultSet rs;/* * * * */@Testpublic void Insert () {//TODO auto-generated method stub//Create SQL statement sql= "Insert into T1 (Name,password) VALUES (?,?) "; /Create an Object array object[] object=new object[]{"admin", "123456"};//Execute SQL Statement mysqlcon.dosql (SQL, object);//Gets the number of rows affected i= Mysqlcon.getupdatecount ();//Determine if the insertion succeeds if (i!=-1) {System.out.println ("Data insertion succeeded! ");} ELSE{SYSTEM.OUT.PRINTLN ("Data insertion failed!") ");} Close link mysqlcon.getclose ();} /* * Delete data * */@Testpublic void Delete () {//TODO auto-generated method stub//Create SQL statement sql= "Delete from T1 where id=?"; /Create an Object array object[] object=new object[]{3};//Execute SQL statement mysqlcon.dosql (SQL, object);//Gets the number of rows affected I=mysqlcon.getupdatecount ();//Determine if the deletion succeeds if (i!=-1) {System.out.println ("Data deletion succeeded!") ");} ELSE{SYSTEM.OUT.PRINTLN ("Data deletion failed!") ");} Close link mysqlcon.getclose ();} /* * UPDATE data * */@Testpublic void update () {//TODO auto-generated method stub//Create SQL statement sql= "update t1 set password=? where NA Me=? "; /Create an Object array object[] object=new object[]{"One", "admin"};//Execute SQL Statement mysqlcon.dosql (SQL, object);//Gets the number of rows affected i= Mysqlcon.getupdatecount ();//Determine if the data is updated successfully if (i!=-1) {System.out.println ("Data Update succeeded! ");} ELSE{SYSTEM.OUT.PRINTLN ("Data update failed!") ");} Close link mysqlcon.getclose ();} /* * TRAVERSE data * */@Testpublic void Select () {//TODO auto-generated method stub//Create SQL statement sql= "SELECT * from T1";//Execute SQL statement MYSQLC On.dosql (SQL, NULL);//Get result set rs=mysqlcon.getrs ();//Determine if the result set is empty if (rs!=null) {try {//moves the cursor to the end of the result set, note that rs.afterlast () cannot be used here Otherwise, a null value. Rs.last ();//Gets the result set row number I=rs.getrow ();//Determines whether the result set exists if (i>0) {//moves the cursor to the end of the result set Rs.beforefirst ();//loops through all rows while (Rs.next () {//traverse the contents of each line element string name=rs.getstring ("name"); String password=rs.getstring ("password");//Print the result System.out.println in the console ("Name:" +name+ "Password:" +password);}} ELSE{SYSTEM.OUT.PRINTLN ("The result set is empty! ");}} Catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} ELSE{SYSTEM.OUT.PRINTLN ("Result set does not exist! ");} Close link mysqlcon.getclose ();}}




MySQL database connection and additions and deletions to change Java code implementation (PreparedStatement version)

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.