Individual Learning Notes--01

Record a little of your last summer vacation study

JDBC

JDBC, accessing database through java. A java API that executes sql statements. With JDBC, you can easily connect to the database.

How to connect?

JDBC connecting database can be divided into three steps: creating connection with database, sending statements of operating database, and final result processing. Here are some specific steps.

public static void main(String[] args){
        //C
        String sql1 = "insert into hero values(null,'Ti Mo')";
        execute(sql1);

        //U
        String sql2 = "update hero set name = 'Zoe' where id = 10";
        execute(sql2);

        //D
        String sql3 = "delete from hero where id = 9";
       execute(sql3);
    }
    
public static void excute(String sql) {
	try {
            //Registration driven
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {t
            e.printStackTrace();
        }
        try(	//Use try-with-resource to automatically close the connection, because both Connection and Statement implement the AutoCloseable interface, ResultSet does not need to be shut down specifically, because ResultSet is shut down by hand when Statement is closed.
                //Create connection   
                Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/sanmu2?" +
                        "characterEncoding=UTF-8",
                        "root","123456");
                //Get the execution sql object
                 Statement stmt = conn.createStatement();
                ){
                stmt.execute(sql);
                  //Query results are placed in the result set
                  // String sql = "select *from table name";
       		 	  //  ResultSet resultSet = stmt.executeQuery(sql);
        		  //  while(resultSet.next()){
          		  //   String name = resultSet.getString("name");
         	   	  //   System.out.println(name);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
  }

Keywords: JDBC SQL Database Java

Added by dakkonz on Wed, 09 Oct 2019 10:43:50 +0300