首页 > 代码库 > Statement执行静态SQL语句

Statement执行静态SQL语句

package com.isoftstone.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.Test;

public class MySqlJDBC {
    
    private String url = "jdbc:mysql://127.0.0.1:3306/scott";
    private String user = "root";
    private String password = "root";
    
    @Test
    public void testJDBC(){
        
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        
        try{
            //1、注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            
            //2、创建连接对象
            conn = DriverManager.getConnection(url, user, password);
            
            //3、创建Statement对象
            stmt = conn.createStatement();
            
            //4、准备sql语句
            String updateSql = "CREATE TABLE student(id INT PRIMARY KEY AUTO_INCREMENT,name VARCHAR(20), gender varchar(2))";
            //String querySql = "SELECT * FROM emp";
            
            //5、发送sql语句、执行sql语句
            //rs= stmt.executeQuery(querySql); 查询的sql语句
            int count = stmt.executeUpdate(updateSql); //修改的sql语句
            
            //6、输出结果     查询的sql和修改的sql不要在一起执行
            /*while(rs.next()){
                String empno = rs.getString("empno");
                System.out.println(empno);
            }*/
            
            System.out.println(count);
        
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //7、关闭连接(顺序:后打开的先关闭)
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(stmt != null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

}

 

Statement执行静态SQL语句