开发模式使用的是JSP+Servlet+JavaBean开发模式


第一步 装好数据库。并在数据库中建好需要使用的数据库以及表。

第二步 将数据库连接jar包导入到工程文件中。Eclipse是导入到WebContent/WEB-INF/lib下,MyEclipse是导入到Webroot/WEB-INF/lib下。我用的是mysql-connector-java-5.1.6-bin.jar这个jar包。(此包极为重要!~)

第三步 注册驱动。对数据库进行各种操作的时候,都必须通过JDBC建立应用程序与数据库的连接。下面给出连接函数以及释放连接函数:

public Connection getConnection()      //数据库连接函数
{
Connection conn=null;
String driver="com.mysql.jdbc.Driver";
String dburl="jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8"; //mydb为你的数据库名称
String username="root"; //你的mysql用户名
String password="root"; //你的mysql登录密码
try{
Class.forName(driver); //加载数据库驱动程序
conn=DriverManager.getConnection(dburl,username,password);
}catch(Exception e){e.printStackTrace();}
return conn;
}
public void JdbcFree(Connection conn,Statement st,ResultSet rs) //数据库连接释放函数
{
try { if (rs != null) rs.close();}
catch (SQLException e) {e.printStackTrace();}
finally {
try { if (st != null) st.close();}
catch (SQLException e) {e.printStackTrace();}
finally {
try {if (conn != null) conn.close();}
catch (SQLException e) {e.printStackTrace();}
}
}
}

第四步 在DAO方法中写需要的数据库操作代码,例如登录的代码:

public boolean searchUser(UserBean user){
//按用户名和密码校验用户是否合法
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rst=null;
try{
conn=getConnection();
String strsql="select * from usertable where username=? and password=? and type=?";
pstmt=conn.prepareStatement(strsql);
pstmt.setString(1, user.getUsername());
pstmt.setString(2, user.getPassword());
pstmt.setInt(3, user.getUsertype());
rst=pstmt.executeQuery();
if(rst.next()){
return true;
}
}catch(Exception e){
e.printStackTrace();
return false;
}finally{ //释放资源
JdbcFree(conn,pstmt,rst);
}
return false;
}

第五步 在Servlet中处理DAO方法中的返回值,例如登录成功,则存储Session然后转到登录成功之后的页面。登录失败则提示登录失败。

更多相关文章

  1. vmware12下的centos7 linux 安装 mysql5.17数据库
  2. ASP.NET GridView 绑定 MySql数据库
  3. 在数据库设计中使用用户名作为主键是不是很糟糕?
  4. 如何向mysql数据库添加多个映像?
  5. 获取项目列表的更好方法:缓存序列化数据与数据库查询或其他?
  6. MySQL数据库相关开发入门
  7. MySQL数据库导入或者同步大量数据时数据丢失解决方案
  8. MySQL 转换函数与运算符
  9. php 连接数据库 Warning: mysqli_connect(): (HY000/2002): No s

随机推荐

  1. Android 音频系统:从 AudioTrack 到 Audio
  2. Android开发:使用Fragment改造TabActivity
  3. Android(安卓)新建文件夹、生成文件并向
  4. android POST请求
  5. 解读新一代岗位要求(一) ----------------A
  6. React-Native之android集成支付宝
  7. Android获取屏幕实际高度跟显示高度,判断A
  8. android_camera_002
  9. 选择Android还是IOS开发?
  10. Android中去除标题,全屏,获得屏幕方向及键