[Java] JDBC-mysql connection and addition, deletion, modification, and query operations

Source: Internet
Author: User
Tags driver manager
Document directory
  • Required Preparations
  • Connected theoretical knowledge
  • Connection test
  • Perform SQL operations in Java
Required Preparations 1. Install MySQL. For more information, see http://blog.csdn.net/jueblog/article/details/9499245 、to download the JDBC driver. You can download from the official website, or click the http://download.csdn.net/detail/oyuntaolianwu/5822697 to download 3, in eclipse Java project to create a new Lib folder, copy the prepared jar package in. 4. Right-click the jar package: Build path --> Add to build path connection theoretical knowledge needs to use Java. SQL. *; related classes: Connection class

Establishes connections with specified URLs (including database IP addresses, database names, usernames, and passwords;
Connection conn = drivermanager. getconnection (URL, user, password); drivermanager. getconnection (URL );
Use the driver manager class to obtain the specified URL Connection

String url = "JDBC: mysql: // localhost: 3306/test"; // The Connection URL is JDBC: MySQL // server address/Database Name
Statement class stmt = conn. createstatment ();
Statement object, used to send an SQL statement to the database
Rs = stmt.exe cutequery (SQL) // return the record set object for query
Int COUNT = stmt.exe cuteupdate (SQL) // execute an add, delete, modify, and return int
Stmt.exe cute (SQL) // add, delete, modify, and return a Boolean value (successful or failed)
Resultset class

Record set object to store the record set returned by the executequery () method. Use the related Rs. getstring ("column name") Rs. getint ("column name") and other methods to obtain the value of the specified column. The connection test Java code is as follows:

Package COM. SQL; import Java. SQL. *; public class jdbc0726_base {connection; Statement statement; resultset rset; // return a connection to a specific database. Public connection getconnection () {try {// The Connection URL is JDBC: mySQL // server address/database name, followed by the login username and password connection = drivermanager. getconnection ("JDBC: mysql: // localhost: 3306/test", "root", "Yongqiang");} catch (sqlexception E) {// todo auto-generated catch blocke. printstacktrace ();} return connection;} public static void main (string [] ARGs) {jdbc01__base jdao = new jdbc01__base (); system. out. println (jdao. getconnection ());}}

If the corresponding object address is output instead of an exception, the connection is successful. For example, output: COM. MySQL. JDBC. jdbc4connection @ 200bde uses Java to perform related operations on SQL. [note] the following operations must rely on the getconnection () method above for non-query-type SQL statements

// Non-Query Class public int Update (string SQL) {getconnection (); int COUNT = 0; try {Statement = connection. createstatement (); Count = statement.exe cuteupdate (SQL);} catch (sqlexception e) {// todo auto-generated catch blocke. printstacktrace ();} finally {try {If (statement! = NULL) {statement. Close (); Statement = NULL;} If (connection! = NULL) {connection. Close (); connection = NULL ;}} catch (sqlexception E2) {// todo: handle exception }} return count ;}

Application:

System.out.println(jDao.Update("INSERT INTO t_user(username,password,sex) values('hehe','131','n');"));

If the output value is 1, the operation is successful.

Query SQL statements and return multiple records
// Execute a query SQL statement and return multiple record sets public void qurty (string SQL) {getconnection (); try {Statement = connection. createstatement (); rset = statement.exe cutequery (SQL); system. out. println ("ID \ t" + "realname \ t" + "school \ t"); While (rset. next () {system. out. println (rset. getrow () + "----" + rset. getstring ("ID") + "\ t" + rset. getstring ("realname") + "\ t" + rset. getstring ("school") + "\ t") ;}} catch (sqlexception e) {// todo Au To-generated catch blocke. printstacktrace ();} finally {try {If (statement! = NULL) {statement. Close (); Statement = NULL;} If (rset! = NULL) {rset. Close (); rset = NULL ;}} catch (sqlexception E2) {// todo: handle exception }}}

Example:

Jdao. qurty ("select * From t_user where sex = 'female ';"); system. out. println ("-----------------------------"); jdao. qurty ("select * From t_user;"); system. out. println ("-----------------------------");
Query SQL statements and return a record
// Execute a query SQL statement and return public void qurtybyunique (string SQL) {getconnection (); try {Statement = connection. createstatement (); rset = statement.exe cutequery (SQL); system. out. println ("ID \ t" + "realname \ t" + "school \ t"); If (rset. next () {system. out. println (rset. getint ("ID") + "\ t" + rset. getstring ("realname") + "\ t" + rset. getstring ("school") + "\ t") ;}} catch (sqlexception e) {// todo auto-generated catch blo Cke. printstacktrace ();} finally {try {If (statement! = NULL) {statement. Close (); Statement = NULL;} If (rset! = NULL) {rset. Close (); rset = NULL ;}} catch (sqlexception E2) {// todo: handle exception }}}

Example:

Jdao. qurtybyunique ("select * From t_user where sex = 'female ';"); system. out. println ("-----------------------------"); jdao. qurtybyunique ("select * From t_user;"); system. out. println ("-----------------------------");
Output all data in the form
public void QurtyTest(String sql) {getConnection();try {statement = connection.createStatement();rSet = statement.executeQuery(sql);while (rSet.next()) {System.out.print(rSet.getRow()+ "----" );for (int i = 1; i < 14; i++) {System.out.print(rSet.getString(i) +"\t");}System.out.println();}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally{try {if (statement != null) {statement.close();statement = null;}if (rSet != null) {rSet.close();rSet = null;}} catch (SQLException e2) {// TODO: handle exception}}}

Application Example

jDao.QurtyTest("SELECT * FROM t_user;");
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.