JDBC is used in Java to manipulate a simple instance of a database
- 2020-04-01 03:56:18
- OfStack
Since I haven't written a database application in a long time, here's a review of Java JDBC.
1. Operating a database using Java JDBC generally requires six steps:
(1) establish the JDBC bridge and load the database driver;
(2) connect to the database and obtain the Connection object (using the database Connection address, user name and password);
(3) obtain database Statement object;
(4) perform database operations;
(5) read the result;
(6) close the database connection;
2. Using Java JDBC to operate database (mysql) code:
To connect to mysql database, you need to import the mysql database jar package. This code USES mysql-connector-java-5.1.18-bin.jar.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
public class MyTest {
public static void main(String args[]) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
//Get an instance of mysql-driven
Class.forName("com.mysql.jdbc.Driver").newInstance();
//Get the connection object (provide: address, username, password)
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/Weather","root", "root");
if (!con.isClosed())
System.out.println("Successfully connected ");
else
System.out.println("failed connected");
//Create a Statement, a database object
st = con.createStatement();
//Run the SQL query statement
rs = st.executeQuery("select * from Weather.question_type_1;");
//Read result set
while (rs.next()) {
System.out.println("column1:"+rs.getInt(1));
System.out.println("column2:"+rs.getString(2));
System.out.println("column3:"+rs.getString(3));
System.out.println("column4:"+rs.getString(4));
}
//Close links
con.close();
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
}
}
}