- 概念:Java Database Connectivity 一种Java操作数据库的连接技术
- 步骤:
- 选择驱动:从https://search.maven.org/ 上下载mysql-connector-java.jar
- 编写连接数据库的代码:
- 连接
`//第1步:加载驱动
_Class._forName(“com.mysql.jdbc.Driver”);
- 连接
_//第2步:获得连接
//url username password
_String url = “jdbc:mysql://127.0.0.1:3306/woniuxy?useUnicode=true&characterEncoding=utf8”;
//得到MySQL数据库的连接
_Connection conn = DriverManager._getConnection(url, “root”, “123”);
conn.setAutoCommit(false);_//关闭自动提交
_return conn;`
1. 查询:
1. 普通查询:<br />` _conn _= _ConnecitionUtil.getCon_();<br /> Statement st = _conn_.createStatement();<br /> String sql = "select * from class_info;";<br /> ResultSet rs = st.executeQuery(sql);_//返回结果集_<br /> System._out_.println("id \t名称");<br /> while (rs.next()) {<br /> long id = rs.getLong("id");<br /> String class_name = rs.getString("class_name");<br /> System._out_.println(id + " \t" + class_name);<br /> }<br /> _conn_.close();<br />}`
1. 预处理+单个返回<br />` _conn _= ConnectionUtil._getCon_();<br /> String sql = "select * from class_info where id =?";<br /> _pst _= _conn_.prepareStatement(sql);
String id = "1";<br /> _pst_.setString(1, id);<br /> ResultSet set = _pst_.executeQuery(); _//返回结果集_<br /> _//返回第一行<br /> _set.absolute(1);<br /> _//返回第二列<br />_ String className = set.getString(2);<br /> _conn_.close();
return className;`
3. 增删改<br />`_//返回受影响的行数<br />_rows = _pst_.executeUpdate();`
- 添加事务
DBhelper中:conn.setAutoCommit(false);_//关闭自动提交_
关闭连接前:
conn.commit();_//提交事务_
- 存储过程