JDBC的使用

JDBC开发步骤:

引入MySQL驱动: 在MySQL驱动上单击鼠标右键(驱动已复制到项目下) ---> Build Path   ---->Add  to Buile Path即可。

    1:注册驱动                              

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

    2:获得连接                            

              connection =

DriverManager.getConnection("jdbc:mysql://localhost:3306/shopper","root", "123456");

    3:获取执行SQL语句的对象

              pre = connection.prepareStatement(sql);

              //执行

              rs = pre.executeQuery();

    4:释放资源

           if(rs!=null){

                    try {

                                rs.close();

                    } catch (SQLException e) {

                                    e.printStackTrace();

                    }

                    //java垃圾回收会更快点

                    rs = null;

           }

注意事项: 创建项目前,先改工作空间的编码为utf-8(默认为gbk);

package mysqlConnectivity;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import org.junit.Test;

public class Connectiontivity {

ResultSet rs;

PreparedStatement pre;

Connection connection;

@Test//单元测试的方法必须为public  void   方法名(必须无参){ }

public void connection(){

try {

//加载驱动

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

//获得连接对象

connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/shopper","root", "123456");

//sql语句

String sql = "select * from orderlist ";

//使用预编译

pre = connection.prepareStatement(sql);

//执行语句

rs = pre.executeQuery();

while(rs.next()){

//列数从1开始

System.out.println(rs.getInt(1)+"  "+rs.getString(2));

}

} catch (Exception e) {

e.printStackTrace();

}

//释放资源

if(rs!=null){

try {

rs.close();

} catch (SQLException e) {

e.printStackTrace();

}

//java垃圾回收会更快点

rs = null;

}

if(pre!=null){

try {

pre.close();

} catch (SQLException e) {

e.printStackTrace();

}

//java垃圾回收会更快点

pre = null;

}

if(connection!=null){

try {

connection.close();

} catch (SQLException e) {

e.printStackTrace();

}

//java垃圾回收会更快

connection = null;

}

}

//测试

public static void main(String[] args) {

Connectiontivity connectiontivity  = new Connectiontivity();

connectiontivity.connection();

}

}

你可能感兴趣的:(JDBC的使用)