日期:2014-05-16 浏览次数:20403 次
话不多说,看代码和注释
分5步 1 查找驱动 2 连接数据库 3 查询 4 提交事务 5 关闭链接
ResultSet rec = st.executeQuery(sqlList);
?
int rta = st.executeUpdate(sqlStr);
?
?
package jdbcttest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.jdbc.Driver;
public class JdbcTest {
?public static void main(String[] args){
??String dbDriver ="com.mysql.jdbc.Driver";
??String url="jdbc:mysql://localhost:3306/test";
??String userName="root";
??String password="hello";
??
??try {
???//1 查找驱动
???Class.forName(dbDriver).newInstance();
???//2 设置url 链接mysql
???Connection? conn = DriverManager.getConnection(url,userName,password);
???Statement st = conn.createStatement();
???//3执行查询
???String sqlList = "select * from news_table";
???ResultSet rec = st.executeQuery(sqlList);
???System.out.println(rec.getRow());
???//4提交事务数据
???String sqlStr = "insert into news_table values (57,'insert')";
??? int rta = st.executeUpdate(sqlStr);
??? conn.setAutoCommit(false);
??? conn.commit();
??? if(rta>0){
???? System.out.println("update 运行成功");
??? }
??? //5 关闭链接
???if(st!= null){
?????? st.close();
???}
???if(!conn.isClosed()){
????conn.close();
???}
??} catch (InstantiationException e) {
???e.printStackTrace();
??} catch (IllegalAccessException e) {
???// TODO Auto-generated catch block
???e.printStackTrace();
??} catch (ClassNotFoundException e) {
???// TODO Auto-generated catch block
???e.printStackTrace();
??}catch (SQLException e) {
???// TODO Auto-generated catch block
???e.printStackTrace();
??}?
?}
}