框架应用:Spring framework - JDBC支持
时间:2021-07-01 10:21:17
帮助过:11人阅读
import java.sql.*
;
public class SelectRecords {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"
;
static final String DB_URL = "jdbc:mysql://localhost/jdbc_db"
;
// Database credentials
static final String USER = "root"
;
static final String PASS = "123456"
;
public static void main(String[] args) {
Connection conn =
null;
Statement stmt =
null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver"
);
//STEP 3: Open a connection
System.out.println("Connecting to a selected database..."
);
conn =
DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully..."
);
//STEP 4: Execute a query
System.out.println("Creating statement..."
);
stmt =
conn.createStatement();
String sql = "SELECT id, first, last, age FROM student"
;
ResultSet rs =
stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id"
);
int age = rs.getInt("age"
);
String first = rs.getString("first"
);
String last = rs.getString("last"
);
//Display values
System.out.print("ID: " +
id);
System.out.print(", Age: " +
age);
System.out.print(", First: " +
first);
System.out.println(", Last: " +
last);
}
rs.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=
null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=
null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}
//end try
System.out.println("Goodbye!"
);
}//end main
}
//end JDBCExample
JDBC查询数据库
1.注册数据库信息
2.获取数据库连接
3.执行sql查询
4.关闭数据库连接
jdbcTemplate代码过程
JDBCTemplate替你完成了获取数据库连接以及关闭连接的部分,你以后完成操作只需要关心SQL的业务实现.
1.导入包(包括相应的数据库驱动包)
2.创建对象,设置数据库信息
3.创建jdbcTemplate对象,设置数据源
4.调用jdbcTemplate对象的方法实现操作
jdbcTemplate主要提供方法
execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;
batchUpdate方法用于执行批处理相关语句;
query方法及queryForXXX方法:用于执行查询相关语句;
call方法:用于执行存储过程、函数相关语句。
框架应用:Spring framework - JDBC支持
标签:print update ror url sys selected color pac rgs