JDBC的连接
来源:互联网 发布:ubuntu lamp环境 编辑:程序博客网 时间:2024/05/18 21:07
JDBC的连接:
String driverClassName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mytb";
String username = "root";
String password = "123";
Class.forName(driverClassName);
Connection con = DriverManager.getConnection(url, username, password);
//System.out.println(con);
1、JDBC的增删改:
Statement sta = con.createStatement();
String sql = "insert into stu values('xiaohong','woman',22,'0010')";
int r = sta.executeUpdate(sql);
2、JDBC的查寻:
Statement sta = con.createStatement();
ResultSet res = sta.executeQuery("select * from emp");
while(res.next()){
int empno = res.getInt(1); //得到表的内容
String ename = res.getString("ename");
String job = res.getString("job");
int mg = res.getInt("mgr");
Date hiredate = res.getDate("hiredate");
double sal = res.getDouble("sal");
double COMM = res.getDouble("COMM");
int deptno = res.getInt("deptno");
System.out.println(""+empno+" , "+ename+" , "+job+" , "+mg+" , "+hiredate+" , "+sal+" , "+COMM+" , "+deptno);
}
3、JDBC的关闭:
sta.close();
con.close();
规范样式:
@Test
public void fun() throws Exception {
Connection con = null;
Statement sta = null;
ResultSet res = null;
try {
String driverClassName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mytb";
String username = "root";
String password = "123";
Class.forName(driverClassName);
con = DriverManager.getConnection(url, username, password);
sta = con.createStatement();
String sql = "select * from stu";
res = sta.executeQuery(sql);
while (res.next()) {
System.out.println(res.getObject(1) + " " + res.getObject(2)
+ " " + res.getObject(3) + " " + res.getObject(4));
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (res != null)
res.close();
if (sta != null)
sta.close();
if (con != null)
con.close();
}
}
PreparedStatement:
@Test
public void fun2() throws ClassNotFoundException, SQLException{
String driverClassName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mytb";
String username = "root";
String password = "123";
Class.forName(driverClassName);
Connection con = DriverManager.getConnection(url, username, password);
String sql = "select * from emp where ename = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, "张三");
ResultSet rs = pstmt.executeQuery();
if(rs.next())
System.out.println(rs.getObject(5));
rs.close();
pstmt.close();
con.close();
}
- jdbc连接的连接方式
- db2的jdbc连接
- JDBC连接的方式
- SQLServer2005的JDBC连接
- DB2的JDBC连接
- jdbc数据库的连接
- 我的JDBC连接
- Hive的JDBC连接
- sybase的JDBC连接
- sql2000的jdbc连接
- mysql的JDBC连接
- 常用的jdbc连接
- JDBC的连接
- mysql的jdbc连接
- jdbc的连接
- teradata的jdbc连接
- JDBC数据库的连接
- JDBC的连接
- 文件权限及其设定
- JAVA提高篇(22)--StringReader和StringWriter的用法
- Linux 中 grep 命令的 12 个实践例子
- 基于MPI的文档分类并行程序设计(C)
- Java中值传递和引用传递的区别
- JDBC的连接
- Spring黑马笔记入门三
- 全选和反选
- listview(从网上获取数据)
- java中重载与重写的区别
- Mac下安装虚拟机出现内部错误的解决方案及原因
- 点击地图获取经纬度(基于腾旭地图api)
- 不规则窗口和控件的封装(win32 API)——TinyDlg
- 测试文章发送