JDBC Link database MySQL

Source: Internet
Author: User

 PackageCn.itcast.demo2;Importjava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Statement;Importorg.junit.Test; Public classDemo2 {/** Connect database, get connection even success! * To increase, delete and change the database.*/@Test Public voidFUN1 ()throwsClassNotFoundException, SQLException {/** First, get connection * 1. Prepare four parameters * 2. Load Driver class * 3. Get connection*/        //prepare four parametersString driverclassname = "Com.mysql.jdbc.Driver"; //the format of the JDBC protocol! JDBC: Name of Industry and commerce: Sub-Protocol (stipulated by Industry and commerce)//for MySQL, its sub-protocol structure://Host: Port number/database nameString url = "JDBC:MYSQL://LOCALHOST:3306/MYDB3"; String username= "Root"; String Password= "123"; //Load Driver classClass.forName (driverclassname); //use DriverManager, and save 3 parameters to get connectionConnection con =drivermanager.getconnection (URL, username, password); /** Second, to increase the database, delete, change * 1. Create a sender of statement * > statement statements through Connection objects, which is the function of sending SQL statements to the database! * 2. called its int executeupdate (String sql), which can send DML, DDL*/        //1. Get statement objects by connectionStatement stmt =con.createstatement (); //2. Send SQL statements using Statement! //String sql = "INSERT into Stu VALUES (' itcast_0003 ', ' Wangwu ', ' Male ')";//String sql = "UPDATE stu SET name= ' Zhaoliu ', age=22," +//"gender= ' female ' WHERE number= ' itcast_0003 '";String sql = "DELETE from Stu"; intR =stmt.executeupdate (SQL);    System.out.println (R); }        /*** Query Execution *@throwsClassNotFoundException *@throwsSQLException*/@Test Public voidFun2 ()throwsClassNotFoundException, SQLException {/** First, get connection * Two, get statement, send the SELECT statement * Three, the query returns the "form" to parse! */        /** One, Get connected * 1. Prepare four key connection parameters*/String Driverclassname= "Com.mysql.jdbc.Driver"; String URL= "Jdbc:mysql://localhost:3306/exam"; String username= "Root"; String Password= "123"; /** 2. Load Driver class*/Class.forName (driverclassname); /** 3. Call Drivermanger's getconnection () by the saved three parameters to get the connection*/Connection con=drivermanager.getconnection (URL, username, password); /** Second, get statement, execute SELECT statement * 1. Get Statement object: Connection's Createstatement () method*/Statement stmt=con.createstatement (); /** 2. Call Statement's ResultSet rs = executeQuery (String querysql)*/ResultSet rs= Stmt.executequery ("SELECT * from emp"); /** Three, analysis resultset * 1. Move the line cursor to the first line, you can call the next () method to complete! */         while(Rs.next ()) {//move the cursor down one line and determine if the next line exists!             intEmpno = Rs.getint (1);//get the value of the column by column number! String ename = rs.getstring ("ename");//get the value of the column by column name            DoubleSal = rs.getdouble ("Sal"); System.out.println (Empno+ "," + ename + "," +Sal); }                /** Four, close the resources * reverse off*/Rs.close ();        Stmt.close (); Con.close ();//this stuff, must be closed, not shut dead!     }        //Normalization@Test Public voidFUN3 ()throwsException {Connection con=NULL;//Defining ReferencesStatement stmt =NULL; ResultSet RS=NULL; Try {            /** One, Get connected*/String Driverclassname= "Com.mysql.jdbc.Driver"; String URL= "Jdbc:mysql://localhost:3306/exam"; String username= "Root"; String Password= "123";            Class.forName (Driverclassname); Con= drivermanager.getconnection (URL, username, password);//instantiation of                        /** Second, create statement*/stmt=con.createstatement (); String SQL= "SELECT * from emp"; RS=stmt.executequery (SQL); Rs.last ();//move the cursor to the last lineSystem.out.println (Rs.getrow ());                        Rs.beforefirst (); /** Three, loop through RS, print the data * * getString () and GetObject () is universal! *///While (Rs.next ()) {//System.out.println (Rs.getobject (1) + ","//+ rs.getstring ("ename") + "," + rs.getdouble ("Sal"));//            }                        intCount =rs.getmetadata (). getColumnCount ();  while(Rs.next ()) {//traversing rows                 for(inti = 1; I <= count; i++) {//traversing ColumnsSystem.out.print (rs.getstring (i)); if(I <count) {System.out.print (", ");            }} System.out.println (); }                    } Catch(Exception e) {Throw NewRuntimeException (e); } finally {            //Close            if(rs! =NULL) Rs.close (); if(stmt! =NULL) Stmt.close (); if(Con! =NULL) Con.close (); }            }}

JDBC Link database MySQL

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.