jdbc

来源:互联网 发布:淘宝活动广场在哪 编辑:程序博客网 时间:2024/06/05 22:23

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

 

public class TestJdbc {

         public static voidmain(String[] args) {

                  

                   try {

                            //1.注册驱动,加载驱动

                            Class.forName("com.mysql.jdbc.Driver");

 

                            //2获取连接对象

                            /**

                             * url(统一资源定位符)jdbc:mysql://localhost:3306/lol

                             * user:            用户名      root

                             * password:   密码   root

                             */

                            Connectionconn=DriverManager.getConnection("jdbc:mysql://localhost:3306/lol","root", "root");

 

                            //3.查看是否连接成功

                            if(conn!=null){

                                     System.out.println("数据库连接成功");

                            }

                            //需要发送sql语句到数据库进行执行,获取发送sql语句的工具

 

                            //4.通过连接对象获取执行sql语句的工具

                            Statement st= conn.createStatement();

 

                            //5.定义sql语句

                            String sql= "select * from hero";

                            //6.把sql语句交给执行工具来执行

                            //查询的结果是一个结果集合,包含多条记录

                            ResultSet rs= st.executeQuery(sql);

 

                            //7.遍历结果集

                            System.out.println("name\tdegree\tspeed\t");

                            //next方法,如果当前行有效,返回true,无效返回false

                            while(rs.next()){

                                     //根据数据库列名获取数据

                                     /*Stringname = rs.getString("name");

                                     Stringdegree = rs.getString("degree");

                                     Stringspeed = rs.getString("speed");*/

                                     //根据列的顺序来拿

                                     Stringname = rs.getString(1);

                                     Stringdegree = rs.getString(2);

                                     Stringspeed = rs.getString(3);

                                     System.out.println(name+ "\t" + degree + "\t" + speed);     

                            }

 

                            //8.释放资源,先开的后关,后开的先关

                            rs.close();

                            st.close();

                            conn.close();

                   } catch (ClassNotFoundExceptione) {

                            // TODOAuto-generated catch block

                            e.printStackTrace();

                   } catch (SQLExceptione) {

                            // TODOAuto-generated catch block

                            e.printStackTrace();

                   }

         }       

}

原创粉丝点击