Java Web开发中使用Mysql数据库

开发模式使用的是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然后转到登录成功之后的页面。登录失败则提示登录失败。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值