首页 > 数据库技术 > 详细

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

时间:2014-11-13 23:44:37      阅读:435      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/liuwt365/p/4095994.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!