I was a junior in postgraduate entrance examination. I didn't want to write a blog. It was a bit of a waste of time. After thinking about it, I used the fragmented time to write.
Many newbies, maybe new to the idea, think wow, so powerful, that's true. But it may not be so easy to use, here, I will briefly introduce what the title says.
1. First, create a database under mysql named: studentdbtest, and create a table named: Student; as shown below:
2. Open the idea and create a work process named: project02_dbtest (I chose java Enterprise -> web application, that is, a web project is created, of course, other projects can also be created) As shown in the figure:
3. Next, you need to import the mysql jar package, as shown in the figure, first, in the web_INF directory, create a new lib package (Directory), import the mysql driver (copy and paste the mysql jar package you downloaded into the lib package), Then, a very important step, select the mysql jar package just imported, right-click, select Add as Library, a window will pop up, select ok . So far, all the preparatory work has been done, the next step is to code the code.
4. The CRUD package is created under src, and a query query.java is created, as shown in the figure. I will not explain the following code, and the comments are also very clear.
Code part:
public class query { public static void main(String[] args) throws ClassNotFoundException, SQLException { //1. Register the driver of the database // Driver driver=new com.mysql.jdbc.Driver(); // DriverManager.registerDriver(driver); Class.forName("com.mysql.jdbc.Driver"); //2. Get database connection String url="jdbc:mysql://localhost:3306/StudentdbTest?useSSL=false"; Connection connection = DriverManager.getConnection(url, "root", "root123"); //3. Get the object of the database Statement statement = connection.createStatement(); String sql="select *from student"; ResultSet resultSet = statement.executeQuery(sql); // Statement statement = JDBCUtil.getConnection.createStatement(); // String sql="select *from student"; // ResultSet resultSet = statement.executeQuery(sql); //4. Traverse the result set and take out the data while(resultSet.next()){ String p_id = resultSet.getString("P_Id"); String p_name = resultSet.getString("P_Name"); System.out.println("学号:"+p_id+"姓名:"+p_name); } //5. Close the database connection resultSet.close(); statement.close(); connection.close(); //JDBCUtil.getConnection.close(); } }
5. As for the additions, deletions and modifications, they are almost the same, so I will not write them here.