标签:style blog java 使用 os strong
通过类的名字,把类(元数据对象)加载到内存中,加载驱动,由于是对数据流做操作,一定要加异常处理,后面也是
<span style="white-space:pre"> </span>// 通过类的名字,把类(元数据对象)加载到内存中
<span style="white-space:pre"> </span>Class.forName("com.mysql.jdbc.Driver");
创建一个数据库链接,getConnection方法中的第一个参数是指数据库类型和所操作数据库的名称,第二个参数是指用户名,第三个参数是指password<密码>
<span style="white-space:pre"> </span>Connection conn = DriverManager.getConnection( <span style="white-space:pre"> </span>"jdbc:mysql://localhost:3306/score", "root", "123456");然后创建一个Statement对象
<span style="white-space:pre"> </span>Statement stm = conn.createStatement();
<span style="white-space:pre"> </span>//执行增、删、改语句,返回int型,受影响的行数 stm.executeUpdate(strSql); //返回一个ResultSet对象,其实就是一个表或者视图 rst = stm.executeQuery(strSql);
<span style="white-space:pre"> </span>//输出结果
while(rst.next()) {// 游标下移一行
System.out.println(rst.getString("Sid") + "\t" + rst.getString("Sname"));
} <span style="white-space:pre"> </span><pre name="code" class="java"><span style="white-space:pre"> </span>finally {
//打开是先打开Connection,再打开ResultSet
//关闭是反的关闭
if(rst != null) {
try {
rst.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(stm != null) {
try {
stm.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}package JDBC_Study;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class PreparedStatementDemo {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rst = null ;
String strSql = "select * from student where sid = ?";
try {
// 通过类的名字,把类(元数据对象)加载到内存中
Class.forName("com.mysql.jdbc.Driver");
//
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/score", "root", "123456");
//执行增、删、改语句,返回int型,受影响的行数
// pStm.executeUpdate();
//返回一个ResultSet对象,其实就是一个表或者视图
stmt = conn.prepareStatement(strSql);
stmt.setString(1, "100081");
rst = stmt.executeQuery();
//输出结果
while(rst.next()) {// 游标下移一行
System.out.println(rst.getString("Sid") + "\t" + rst.getString("Sname"));
}
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
//打开是先打开Connection,再打开ResultSet
//关闭是反的关闭
if(rst != null) {
try {
rst.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
JDBC学习第一站之Statement与PreparedStatement,布布扣,bubuko.com
JDBC学习第一站之Statement与PreparedStatement
标签:style blog java 使用 os strong
原文地址:http://blog.csdn.net/ye_scofield/article/details/38061329