mysql jdbc驱动怎么用_mySql jdbc 驱动 使用-心得体会

1.首先,导入驱动mysql-connector-java-5.1.6-bin.jar。

2.创建数据库链接类DBConnection:

public class DBConnection {

private static final String DRIVER_CLASS="com.mysql.jdbc.Driver";

private static final String DATABASE_URL="jdbc:mysql://localhost:3306/数据库名?user=root&password=sa&useUnicode=true&characterEncoding=GB2312";

public static Connection getConnection(){

Connection con = null ;

try {

Class.forName(DRIVER_CLASS);

con = DriverManager.getConnection(DATABASE_URL);

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return con;

}

public static void closeResultSet(ResultSet rs){

if(rs != null){

try {

rs.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

public static void closeStatement(Statement stmt){

if(stmt != null){

try {

stmt.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

public static void closePreparedStatement(PreparedStatement pstmt){

if(pstmt != null){

try {

pstmt.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

public static void closeConnection(Connection con){

if(con != null){

try {

con.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

}

3.创建测试类TestMySqlJDBC:

public class TestMySqlJDBC {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

Connection con = DBConnection.getConnection();

if(con==null){

System.out.println("con is null ");

}else{

System.out.println("con is not null");

}

try {

Statement stmt = con.createStatement();

String sql = "select * from student";

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()){

System.out.println(rs.getString("stuName"));

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值