The following articles mainly describe the test steps for connecting to the MySQL database using java, including introduction to the loading driver, the following describes how to connect a database to a MySQL database and how to execute SQL commands.
Step 1. Load the driver:
1. First, find the name of the Driver class to be used, such as com. MySQL. jdbc. Driver. You can use the command line parameter method to import data. You can use the classpath method to modify data. It is best to use the jar package method to import data.
2. register the driver in the following ways:
1. Set the jdbc. drivers attribute using command line parameters
2. Set System Properties for method calls: System. setProperty ("jdbc. drivers", driver); driver = "com. MySQL. jdbc. Driver"
3. Load the driver Class: Class. forName (driver );
4. Use attribute files
Step 2. Open a database and connect to MySQL
Create a connection:
- Connection conn = DriverManager.getConnection(url, username, pwd);
Url: specified data source, "jdbc: MySQL: // localhost/test"
Step 3. Run the SQL command
1. Create a statement object (to connect to the MySQL database conn in the previous step ):
- Statement st = conn.createStatement();
2. Use this object to execute the statement:
- st.executeQuery("select * from test");executeUpdate();
Note that the select query must use executeQuery ();
Code
- import java.sql.*;public class DbConnTest { /** * @param args */ public static void main(String[] args)
{ // TODO Auto-generated method stub String driver = "com.MySQL.jdbc.Driver"; String url = "jdbc:MySQL:
//localhost/test"; String user = "root"; String password = "admin"; try{ //Class.forName(driver);
System.setProperty("jdbc.drivers", driver);
Connection con = DriverManager.getConnection(url, user, password); String sql = "select * from pet;";
Statement stmt = con.createStatement(); ResultSet rset = stmt.executeQuery(sql);
while (rset.next()){ System.out.println(rset.getString("name") + "
" + rset.getString("owner")); } }catch (Exception e) { e.printStackTrace(); } }}
The above content is an introduction to the test of connecting to the MySQL database by using java. I hope you will get some benefits.