[Mysql] add, delete, modify, and query Mysql Databases in Java, Java System class, And javamysql

Source: Internet
Author: User

[Mysql] add, delete, modify, and query Mysql Databases in Java, Java System class, And javamysql

This part is also the content of the so-called JDBC and website data sources. It makes the name very similar. In fact, it is only the content of adding, deleting, modifying, and querying the Mysql database in Java. It is very simple. I have written so much Mysql content before, but I have not summarized it well. Today, we will implement the addition, deletion, modification, and query of the Mysql database in Java. We can use Java to retrieve the system name and time of the current system and complete a small example.


I. Basic Objectives

First, there is an empty table named testtable In the Mysql database. id is an auto-incrementing column. username and class are all text columns, but all the numbers in the class, that is, integer, this column will be taken out in Java as an integer.


Every time you run the program, the program inserts the current system name (not changed) and the current system's hour, minute, and second (changed) into the username. The system will not be inserted in milliseconds, years, months, and days, this is not a problem because it is out of the Integer Range, but to avoid the complexity of the program, we will not introduce [Java] since we have BigInteger, I no longer have to worry about the size of the data to be processed (click to open the link.



Ii. Production Process

1. First, Java needs to connect to the Mysql database, which is not as good as asp-linked Access and c-linked SQL Server. After all, it is people with Microsoft, although we still often use windows programming, development, but we also need to download a mysql-connector-java-5.1.32.jar from the Internet, this thing in the Mysql official website has no way to test, there is no cross-platform version in it. For the msi installation file of the Windows version, search for mysql-connector-java on the Internet. The version number is not important, I have never seen code writing correctly and connection failure.

2, then, in your project directory to create a new lib folder, put this mysql-connector-java-5.1.32.jar in, do not call this name can also, but it is said that the industry basically get like this, some companies may even give it to the manager who is increasingly not writing code.


3. Right-click your project and select "properties"


4. On the Java Build Path tab, select Add JARs..., find the mysql-connector-java-5.1.32.jar you just put in the lib folder, and click OK to start to write the code happily.


5. First, introduce the following at the beginning:

import java.sql.*;import java.text.*;import java.util.*;import java.util.Date;
To get the current time, the ArrayList dynamic array is also used below. What is this, please refer to my previous collection classes in [Java] Java -- upgraded data structure in Java (click to open the link), and import java must be introduced in the file header. util. *; because the SQL class also contains the Date () class, you must add an additional statement to import java. util. date; remove ambiguity, import java. text. *; it is also used for later processing of the current time of the system. Otherwise, you can only get the number of milliseconds from the New Year's Day in 1970 to the present.

6. Write a database connection class Dbcon.

Class Dbcon {// connect to the database and create a Class independently. You do not need to write so many public Connection getCon () {Connection con = null each time you operate the database. try {class. forName ("com. mysql. jdbc. driver "); // Where test is the database to be linked, user is the database username, and password is the database password. // 3306 is the mysql port number, which is usually the long string of parameters following this // to prevent garbled characters, you do not need to add a set names UTF8String url = "jdbc: mysql: // localhost: 3306/test? UseUnicode = true & characterEncoding = utf8 & useOldAliasMetadataBehavior = true "; String user =" root "; String password =" root "; con = DriverManager. getConnection (url, user, password);} catch (Exception e) {e. printStackTrace () ;}return con ;}}

7. How to operate the database is the core of the entire program:

Public class JavaDbTest {public static void main (String [] args) {// Connection con = new Dbcon () of the database (). getCon (); String SQL = null; // this way, you can obtain the name of the current operating system // The start of the database insertion Operation. If you modify the name, you will not do it, modify the SQL statement String username = System in the following SQL String. getProperty ("OS. name "); // you can obtain the current time, but import java must be introduced in the file header. util. *; // because the SQL class also contains the Date () class, you must add an additional statement to import java. util. date; remove ambiguity String classString = new SimpleDateFormat ("hhmmss "). format (new Date (System. currentTimeMillis ())). toString (); SQL = "INSERT INTO testtable (username, class) VALUES ('" + username + "', '" + classString + "')"; // note: the statement used to operate on the database is Insert into. The statement "update" and "select" for database query are different in Java. // The statement used to operate the database is con.createstatement(cmd.exe cute (SQL); // The data database is rsw.con.preparestatement (); and the query result must be connected by the ResultSet object rs try again con.createstatement(cmd.exe cute (SQL); // after the result is completed, the person takes the door con. close ();} catch (Exception e) {e. printStackTrace ();} SQL = "select * from testtable"; ResultSet rs = null; // The ArrayList that stores the query results must be placed on the periphery of try-catch, note the valid range of variables: ArrayList <Integer> idArraylist = new ArrayList <Integer> (); ArrayList <String> usernameArraylist = new ArrayList <String> (); arrayList <Integer> classArraylist = new ArrayList <Integer> (); try {rs = con.preparestatement(sql0000.exe cuteQuery (); // The result of this loop is to read the entire query structure while (rs. next () {// retrieve all columns and print them out to idArraylist. add (rs. getInt ("id"); usernameArraylist. add (rs. getString ("username"); // even if the column of the class is full of numbers, this column uses varchar for storage. // if you want to treat the class as an integer, therefore, rs is unavailable. getInt, which can only be retrieved from String and then erased as an integer rs. getString ("class"); classArraylist. add (Integer. parseInt (rs. getString ("class");} // after completing the preceding steps, the person takes the door to con. close ();} catch (Exception e) {e. printStackTrace ();} System. out. println ("id username class"); for (int I = 0; I <idArraylist. size (); I ++) System. out. println (idArraylist. get (I) + "" + usernameArraylist. get (I) + "" + classArraylist. get (I ));}}

8. At this point, the entire program is connected like this:

Package test; import java. SQL. *; import java. text. *; import java. util. *; import java. util. date; class Dbcon {// connect to the database and open a class independently. You do not need to write so many public Connection getCon () {Connection con = null for each Connection to the database; try {Class. forName ("com. mysql. jdbc. driver "); // Where test is the database to be linked, user is the database username, and password is the database password. // 3306 is the mysql port number, which is usually the long string of parameters following this // to prevent garbled characters, you do not need to add a set names UTF8String url = "jdbc: mysql: // localhost: 3306/test? UseUnicode = true & characterEncoding = utf8 & useOldAliasMetadataBehavior = true "; String user =" root "; String password =" root "; con = DriverManager. getConnection (url, user, password);} catch (Exception e) {e. printStackTrace ();} return con;} public class JavaDbTest {public static void main (String [] args) {// The Connection con = new Dbcon () of the database (). getCon (); String SQL = null; // this way, you can obtain the name of the current operating system // The start of the database insertion Operation. If you modify the name, you will not do it, modify the SQL statement String username = System in the following SQL String. getProperty ("OS. name "); // you can obtain the current time, but import java must be introduced in the file header. util. *; // because the SQL class also contains the Date () class, you must add an additional statement to import java. util. date; remove ambiguity String classString = new SimpleDateFormat ("hhmmss "). format (new Date (System. currentTimeMillis ())). toString (); SQL = "INSERT INTO testtable (username, class) VALUES ('" + username + "', '" + classString + "')"; // note: the statement used to operate on the database is Insert into. The statement "update" and "select" for database query are different in Java. // The statement used to operate the database is con.createstatement(cmd.exe cute (SQL); // The data database is rsw.con.preparestatement (); and the query result must be connected by the ResultSet object rs try again con.createstatement(cmd.exe cute (SQL); // after the result is completed, the person takes the door con. close ();} catch (Exception e) {e. printStackTrace ();} SQL = "select * from testtable"; ResultSet rs = null; // The ArrayList that stores the query results must be placed on the periphery of try-catch, note the valid range of variables: ArrayList <Integer> idArraylist = new ArrayList <Integer> (); ArrayList <String> usernameArraylist = new ArrayList <String> (); arrayList <Integer> classArraylist = new ArrayList <Integer> (); try {rs = con.preparestatement(sql0000.exe cuteQuery (); // The result of this loop is to read the entire query structure while (rs. next () {// retrieve all columns and print them out to idArraylist. add (rs. getInt ("id"); usernameArraylist. add (rs. getString ("username"); // even if the column of the class is full of numbers, this column uses varchar for storage. // if you want to treat the class as an integer, therefore, rs is unavailable. getInt, which can only be retrieved from String and then erased as an integer rs. getString ("class"); classArraylist. add (Integer. parseInt (rs. getString ("class");} // after completing the preceding steps, the person takes the door to con. close ();} catch (Exception e) {e. printStackTrace ();} System. out. println ("id username class"); for (int I = 0; I <idArraylist. size (); I ++) System. out. println (idArraylist. get (I) + "" + usernameArraylist. get (I) + "" + classArraylist. get (I ));}}


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.