Simple test of JDBC connection MySQL database in Java

Source: Internet
Author: User
Tags getmessage rollback

I. Reference Library

Maven Library: mysql:mysql-connector-java:6.0.6

Second, the SDK environment

JAVA JDK10

Third, the test code

  

 PackageCom.mysql.mysqlconnector;ImportJava.sql.*; Public classDbmain { Public Static voidMain (string[] args)throwsclassnotfoundexception {System.out.println ("Data Base connection test:");        Connection Connection; var driver= "Com.mysql.cj.jdbc.Driver"; var URL= "jdbc:mysql://127.0.0.1:3306/testdb?characterencoding=utf8&useunicode=true&usessl=false& Servertimezone=asia/shanghai "///Note that the new requirements must be added servertimezone var user= "Root"; var password= "Password"; Try{class.forname (driver); var conn=drivermanager.getconnection (URL, user, password); if(!conn.isclosed ()) System.out.println (String.Format ("Conection to%s successfully.", url)); //statement Executing SQL that cannot use parametersStatement Statement =conn.createstatement (); ResultSet ResultSet= Statement.executequery ("SELECT * FROM student WHERE rowid<999"); ResultSetMetaData MD=Resultset.getmetadata (); var columnCount=Md.getcolumncount ();  for(var i = 1; I <= columnCount; i++) {//Note the starting numberSystem.out.println ("---------------------"); System.out.print (Md.getcolumnclassname (i)+ "\ T");//java.lang.StringSystem.out.print (Md.getcolumndisplaysize (i) + "T");//255System.out.print (Md.getcolumnname (i) + "T");//nameSystem.out.print (Md.getcolumntype (i) + "T");// ASystem.out.print (Md.getcolumntypename (i) + "T");//VARCHARSystem.out.println (Md.getcolumnclassname (i) + "T");//java.lang.String            }             while(Resultset.next ()) { for(var i = 1; I <= columnCount; i++) {System.out.print (Resultset.getobject (i)); System.out.print ("\ T");            } System.out.println ();            } statement.close (); //preparestatementvar preparestatement = conn.preparestatement ("SELECT * from student WHERE rowid<?"); Preparestatement.setint (1, 999);//note here that the columnindex in JDBC is starting from 1. ResultSet results =Preparestatement.executequery ();  while(Results.next ()) {var rowId= Results.getint (1);//note here that the columnindex in JDBC is starting from 1. var name = results.getstring (2); var age= Results.getint (3); System.out.println (RowId+ "\ T" + name + "\ T" +Age );            } preparestatement.close (); //Insertvar insertpreparestatement = conn.preparestatement ("INSERT into student (name,age) VALUES (?,?)", Statement.return_generated_keys); Insertpreparestatement.setstring (1, "Sindrol"); Insertpreparestatement.setint (2, 28); if(Insertpreparestatement.executeupdate () > 0) {ResultSet GK=Insertpreparestatement.getgeneratedkeys (); if(Gk.next ()) System.out.println ("Insert into success. Primary key RowId = "+ Gk.getint (" Generated_key "));            } insertpreparestatement.close (); //Batch commit.Conn.setautocommit (false);//Stop Auto-commit first. var batchpreparestatement = conn.preparestatement ("INSERT into student (name,age) VALUES (?,?)", Statement.return_generated_keys);  for(inti = 0; I < 5; i++) {batchpreparestatement.setstring (1, "Lingling_" +i); Batchpreparestatement.setint (2, (20 +i));            Batchpreparestatement.addbatch (); }            Try{var intarrs=Batchpreparestatement.executebatch ();  for(Var eff:intarrs) System.out.println ("EFF:" +eff); Conn.commit ();
Batchpreparestatement.clearbatch ();//After submission, empty batch. var keys=Batchpreparestatement.getgeneratedkeys (); while(Keys.next ()) {intRowId = Keys.getint ("Generated_key"); System.out.println ("rowID:" +rowId); } } Catch(Exception ex) {System.out.println ("Commit failed and would rollback:" +ex.getmessage ()); Conn.rollback (); }finally{batchpreparestatement.close (); } if(!conn.isclosed ()) conn.close (); } Catch(Exception ex) {System.out.println ("SQL Operation exception:" +ex.getmessage ()); } }}

Four, the Operation effect

"C:\Program Files\java\jdk-10\bin\java"-javaagent:d:\applicaton\devtools\jetbrains\intellijidea\lib\idea_rt.jar =33464:d:\applicaton\devtools\jetbrains\intellijidea\bin-dfile.encoding=utf-8-classpath D:\Project\JavaProject\ Javademo\out\production\javademo; C:\Users\yungoal\.m2\repository\com\alibaba\fastjson\1.2.16\fastjson-1.2.16.jar; C:\Users\yungoal\.m2\repository\mysql\mysql-connector-java\6.0.6\mysql-connector-java-6.0.6. Jar Com.mysql.mysqlconnector.DbMainData Base Connection test:conection to Jdbc:mysql://127.0.0.1:3306/testdb?characterencoding=utf8&useunicode=true&usessl=false&servertimezone=asia/ Shanghai successfully.---------------------Java.lang.IntegerROWID 4INT Java.lang.Integer---------------------java.lang.String255 name 12VARCHAR java.lang.String---------------------Java.lang.IntegerAge 4INT Java.lang.Integer1 Songxingzhu 2 wanghaixing 3 Sindrol 4 Sindrol 5 Sindrol 28 6 Sindrol 7 Sindrol 8 Sindrol 9 lingling_0 lingling_1 Lin Gling_2 lingling_3 lingling_4 1 songxingzhu 272 wanghaixing 283 Sind     Rol 284 Sindrol 285 sindrol 286 sindrol 287 Sindrol 288 Sindrol 289 Lingling_0 2010 Lingling_1 2111 lingling_2 2212 lingling_3 2313 lingling_4 24Insert into success. Primary KEY RowId=14eff:1eff:1eff:1eff:1eff:1rowID:15rowID:16rowID:17rowID:18rowID:19Process finished with exit code0

  

Simple test of JDBC connection MySQL database in Java

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.