Java之JDBC小Demo(非Preparedstatement)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011304490/article/details/84558684
import java.sql.*;

public class mytest {
    public static void main(String[] args)
    {
        Connection con = null;
        Statement createSM = null;
        ResultSet rs = null;

        try
        {
            //1、注册驱动
            //DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            Class.forName("com.mysql.jdbc.Driver");//这句某版本后可以省略,会自动注册
            //2、建立连接
            con = DriverManager.getConnection("jdbc:mysql://localhost/myblog?useSSL=false","root","mysql");
            //3、创建statement
            createSM = con.createStatement();
            //4、执行语句获得结果集
            String sql = "select * from user;";
            rs = createSM.executeQuery(sql);
            //5、遍历结果集
            while(rs.next())
            {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String pwd = rs.getString("pwd");
                System.out.println("id:"+id+",name:"+name+",pwd:"+pwd);
            }
        }
        catch (Exception e){}
        finally
        {
            //6、关闭资源
            try{
                if(rs != null){
                    rs.close();
                }
            }
            catch (SQLException e){}
            try{
                if(createSM != null){
                    createSM.close();
                }
            }
            catch (SQLException e){}
            try{
                if(con != null){
                    con.close();
                }
            }
            catch (SQLException e){}
        }
    }
}

猜你喜欢

转载自blog.csdn.net/u011304490/article/details/84558684