设为首页 加入收藏

TOP

mysqljdbc入门学习(二)
2015-11-21 01:58:37 来源: 作者: 【 】 浏览:2
Tags:mysqljdbc 入门 学习
中,我们应该将最终必须要执行的代码放到finally当中
释放资源的代码
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}

if(stmt!=null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}

if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}


7. 防止 sql 注入
在 service 层进行逻辑判断
使用PreparedStatement对象

package cn.test.jdbc.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.Properties;



import com.mysql.jdbc.Driver;

public class JDBCDemo {
//连接数据库的url的写法
//jdbc主协议,mysql是子协议
//jdbc协议:数据库子协议://主机:端口号:/数据库名
private String url="jdbc:mysql://localhost:3306/day15";
//用户名
String username = "root";
//密码
String password = "Name-66437";
@Test
public void main(String [] args) throws SQLException{
//1.创建一个驱动程序的类对象
Driver driver = new com.mysql.jdbc.Driver();
//设置用户名和密码
Properties props = new Properties();
props.setProperty("username", username);
props.setProperty("password", password);

//2.连接数据库
Connection conn = driver.connect(url, props);
Statement stmt = conn.createStatement();
String sql = "select * from student";
ResultSet rs = stmt.executeQuery(sql);
//7.处理结果集
System.out.println("id | name | password | email | birthday");
while(rs.next()) {
// 有第一行
int id = rs.getInt("id"); // 通过列名取值比较直观
String name = rs.getString("name");
String psw = rs.getString("password");
String email = rs.getString("email");
Date birthday = rs.getDate("birthday");
System.out.println(id + " | " + name + " | " + psw + " | " + email + " | " + birthday);
}
//释放资源的代码
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}

if(stmt!=null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}

if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}

?

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇ubuntumysql无法启动简单排查 下一篇MySQL与Navicat的连接

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: