JDBC:(Java DataBase Connectivity,java数据库连接),使数据库开发人员能够编写数据库应用程序.
1)JDBC操作详细步骤
①加载驱动
Class.forName("com.mysql.jdbc.Driver");
② 获取连接
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:端口号/数据库名", "账号", "密码");
一般端口号:3306
账号:root
密码:root
③准备sql
String sql = "select * from user where name=?";//列举,查询指定姓名学生的信息
④创建预处理对象
prepareStatemen ps = con.prepareStatement(sql);
⑤对预处理对象赋值
ps.setString(1, name);//1表示sql第1个问号处赋值
⑥执行sql
//若为修改数据则采用:int update = ps.executeUpdate();其中update表示1行被修改
ResultSet ex = ps.executeQuery();
UserBean user = null;
if (ex.next()) {
user = new UserBean();
user.setName(ex.getString(1));
user.setPassword(ex.getString(2));
user.setAge(ex.getInt(3));
}
⑦资源回收
if (con != null)
con.close();
if (ps != null)
ps.close();
if (ex != null)(可能不需要)
ex.close();
2)注意容易出错的地方
导包:
import java.sql...
import java.util...
不导:
import com.mysql.jdbc...
import java.awt.List....
3)遍历Link的三种方式
①for (UserBean userBean2 : selectAll) {
System.out.println(userBean2);
}
②for (int i = 0; i < selectAll.size(); i++) {
System.out.println(selectAll.get(i));
}
③Iterator<UserBean> iterator = selectAll.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}