The following example is the simplest example of an ODBC connection to a MySQL database.
General steps:
1. Registration drive;
2. Establish a connection;
3. Create a statement;
4. Processing the results;
5. Release resources.
Attention:
1. Software development environment: MyEclipse 8.5+ MySQL5.1
2. The MySQL driver package needs to be loaded before the code is run;
Database information:
The source code is as follows:
Importjava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Statement;/*********************************** * Test ODBC connection mysql database * MySQL database * login account: Root * Login Password: Toor * * Build database name: TESTODBC * Table name : T_users * Field: * ID int * username VARCHAR 255 * Password VARCHAR 255 * ********** ************************/ Public classOdbc_conn_mysql { Public Static voidMain (string[] args)throwsSQLException {//1. Registration DriverDrivermanager.registerdriver (Newcom.mysql.jdbc.Driver ()); //2. Establish a connectionConnection conn =Drivermanager.getconnection ("Jdbc:mysql://localhost:3306/testodbc", "root", "Toor"); //Create statementStatement st =conn.createstatement (); //EXECUTE StatementResultSet rs = st.executequery ("SELECT * from T_users"); //Processing Results while(Rs.next ()) {//Read and Save database query results intx = Rs.getint ("ID"); String S1= Rs.getstring ("username"); String S2= rs.getstring ("Password"); //Print ResultsSystem.out.println ("id=" +x); System.out.println ("Username=" +S1); System.out.println ("Password=" +S2); } //Freeing ResourcesRs.close (); St.close (); Conn.close (); }}
Run:
Test ODBC connection MySQL database