美文网首页
jdbc驱动

jdbc驱动

作者: XII01 | 来源:发表于2020-05-11 10:14 被阅读0次
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    
    public class JDBCTest {
        public static void main(String[] args) throws Exception {
            Connection connection = null;
            PreparedStatement prepareStatement = null;
            ResultSet rs = null;
    
            try {
                // 加载驱动
                Class.forName("com.mysql.jdbc.Driver");
                // 获取连接
                String url = "jdbc:mysql://127.0.0.1:3306/db_jdbc";
                String user = "root";
                String password = "wang1234";
                connection = DriverManager.getConnection(url, user, password);
                // 获取statement,preparedStatement
                String sql = "select * from tb_user where id=?";
                //  防止sql 注入
                prepareStatement = connection.prepareStatement(sql);
                // 设置参数
                prepareStatement.setLong(1, 1l);
                // 执行查询
                rs = prepareStatement.executeQuery();
                // 处理结果集
                while (rs.next()) {
                  
                    System.out.println(rs.getString("name"));
                    System.out.println(rs.getInt("age"));
                }
            } finally {
                // 关闭连接,释放资源
                if (rs != null) {
                    rs.close();
                }
                if (prepareStatement != null) {
                    prepareStatement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:jdbc驱动

          本文链接:https://www.haomeiwen.com/subject/gfbynhtx.html