关于百度BAE 数据库开发步骤

时间:2022-09-22 19:26:07

1、先注册一个百度BAE账号

2、建一个项目,再点击“扩展服务”,创建MySql。


3、打开MyEclipse,分别建立 jsp页面,servlet层,dao层,DBUtils层,代码如下。

3.1 建立 index.jsp

<form name="demo" method="post" action="LoginServlet">
    <table border="1">
    <tr>
    <td>用户名:</td>
    <td><input type="text" name="username"/><td/>
</tr>
    <tr>
<td>密码:</td>
<td><input type="password" name="password"/><td/>
</tr>
<tr>
    <td colspan="2">
    <input type="submit" value="提交">
    <input type="reset" value="取消"/>
    </td>
   </tr>
    </table>
    </form>


3.2 servlet 层

private UserDao userDao = new UserDao();


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


doPost(request, response);
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


String username = request.getParameter("username");
String password = request.getParameter("password");

userDao.add(username,password);
}

}


3.3 dao层

public class UserDao {
private DBHelper helper = new DBHelper();
private Connection conn;
private Statement stat;
private String sql;

public void add(String username, String password){
try {

conn = helper.getConn();
stat = conn.createStatement();

sql="insert into test_mysql(username, password) values('"+username+"','"+password+"')";
System.out.println(sql);
stat.execute(sql);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException("添加数据失败!");
}

}
}


3.4 DBUtil层

public class DBHelper {
public Connection connection = null;
public Statement stmt = null;
public ResultSet rs = null;
public String sql = null;


public String databaseName = "    ";// 这里是数据库名称
public String host = "sqld.duapp.com";
public String port = "4050";
public String username = "      ";// 这里是百度提供的API Key
public String password = "      ";// 这里是百度提供的 密码
public String driverName = "com.mysql.jdbc.Driver";
public String dbUrl = "jdbc:mysql://";
public String serverName = host + ":" + port + "/";
public String connName = dbUrl + serverName + databaseName;

public Connection getConn() {
try {
Class.forName(driverName);
return DriverManager.getConnection(connName, username, password);
} catch (Exception e) {
throw new RuntimeException("数据库链接失败");
}

}
}

3.5 创建 domain层,这里省略

3.6 项目导入 mysql-connector 的jar包


4、将项目Export... 为war 包,用SVN  commit 到百度的服务器上。

5、点击 百度数据库列表 后面的 “phpMyAdmin”,这是DB的可视化平台,可用来调试程序。


这样就基本完成了