JAVA JDBC

作者: 瓦达西瓦卡米哒 | 来源:发表于2018-12-17 23:57 被阅读0次

```

//导入sql下所有类

import java.sql.*;

public class Test {

/**

*  连接数据库需要用到

*  连接本地数据库的数据库的库名

*  定义一个用于连接数据库的类

*  定义一个结果集

*  数据库的账号和密码

*  定义一个用于执行数据库操纵的类

*  sql语句

*/

    private static final StringJDBC_DRIVER ="com.mysql.jdbc.Driver";

    private static final StringDB_URL ="jdbc:mysql://localhost/text";

    private static Connectionconn =null;

    private static  ResultSetrs =null;

    private static final StringUSER ="root";

    private static final StringPASS ="root";

    private static  Statementst =null;

    private static  Stringsql ="select * from Student where Student_Sex = '男' ";

    /**

* 静态方法方便调用

*/

    public static void aaa(){

try {

//强制JVM将com.mysql.jdbc.Driver这个类加载入内存,以便将其注册到DriverManager类上去

            Class.forName(JDBC_DRIVER);

            //连接数据库

            conn = DriverManager.getConnection(DB_URL,USER,PASS);

        }catch (ClassNotFoundException e) {

System.out.println("mysql初始驱动错误");

            e.printStackTrace();

        }catch (SQLException e) {

System.out.println("建立连接失败");

            e.printStackTrace();

        }

}

/**

* 静态方法方便调用

*/

    public static void kaishibiaoyanle(){

//调用方法连接数据库

        aaa();

        //新建一个学生类

        Student student =null;

        try {

//要获取一个可以执行

            st =conn.createStatement();

            //执行sql语句

            rs =st.executeQuery(sql);

            //如果返回的结果集里有值就进入循环

            while (rs.next()){

student =new Student();

                //获取数据库的学生id

                student.setStudent_ID(rs.getString("Student_ID"));

                //获取数据库的学生名字

                student.setStudent_Name(rs.getString("Student_Name"));

                //获取数据库的学生生日

                student.setStudent_Birthday(rs.getDate("Student_Birthday"));

                //获取数据库的学生性别

                student.setStudent_Sex(rs.getString("Student_Sex"));

                //通过重写的toString方法打印获取到的值

                System.out.println(student.toString());

            }

}catch (SQLException e) {

System.out.println("语句地方");

            e.printStackTrace();

        }finally {

try {

//关流

                    if (rs !=null){

rs.close();

                    }

if (st !=null){

st.close();

                    }

if(conn !=null){

conn.close();

                    }

}catch (SQLException e) {

e.printStackTrace();

                }

}

}

public static void main(String[] args) {

//调用方法

        kaishibiaoyanle();

    }

}

```

相关文章

网友评论

      本文标题:JAVA JDBC

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