首页 > 代码库 > MySql用statement实现DDL,DML,DQL的操作Demo

MySql用statement实现DDL,DML,DQL的操作Demo

Demo1

Connection connection=null;        Statement stmt=null;        int result=-1;                try {            Class.forName("com.mysql.jdbc.Driver");                    } catch (ClassNotFoundException e) {            e.printStackTrace();        }                        try {            //创建连接            String url="jdbc:mysql://localhost:3306/jdbcdb";            connection= DriverManager.getConnection(url, "root", "mysql");        } catch (SQLException e) {            e.printStackTrace();        }                try {            //创建Statement            String sql="CREATE TABLE s_user(id INT PRIMARY KEY AUTO_INCREMENT,    NAME VARCHAR(20),PASSWORD VARCHAR(15)) ";             stmt=connection.createStatement();             //执行sql语句,返回受影响行数 ————int值             result= stmt.executeUpdate(sql);        } catch (SQLException e) {            e.printStackTrace();        }                System.out.println("result="+result);                try {            //关闭流            if(stmt!=null)            {                stmt.close();            }                        if(connection!=null)            {                connection.close();            }                    } catch (SQLException e) {            e.printStackTrace();        }

Demo2

Connection connection=null;        Statement stmt=null;        ResultSet rSet=null;        try {            Class.forName("com.mysql.jdbc.Driver");            String url="jdbc:mysql://localhost:3306/jdbcdb";            String user="root";            String password="mysql";            //连接            connection= DriverManager.getConnection(url, user, password);            stmt= connection.createStatement();//statement            String sql="SELECT * from s_user;";            rSet= stmt.executeQuery(sql);//执行sql语句---数据集(类似于map)                        while (rSet.next()) {                //获取值(通过索引)                int id= rSet.getInt(1);                String name=rSet.getString(2);                String pwd=rSet.getString(3);                                System.out.println("id="+id+";name="+name+";pwd="+pwd);                //通过行列号                id=rSet.getInt("id");                name=rSet.getString("name");                pwd=rSet.getString("password");                                System.out.println("~~~~~~~id="+id+";name="+name+";pwd="+pwd);                            }                    } catch

 

MySql用statement实现DDL,DML,DQL的操作Demo