【问题标题】:How to create mysql database in TomCat for an android app?如何在 TomCat 中为 Android 应用程序创建 mysql 数据库?
【发布时间】:2016-11-16 10:04:17
【问题描述】:

谁能指出我学习如何创建 MYSQL 数据库并将其保存在 Tomcat 网络服务器中的方向?该数据库将用于 android 应用程序。 谢谢。

【问题讨论】:

    标签: android mysql tomcat


    【解决方案1】:

    这是一个在 Android 中使用 MySQL 数据库的示例登录应用程序。为了从 Android 设备/模拟器连接到 MySQL 数据库,我将通过 JSON 处理的应用程序向 Servlet 发送 HTTP 请求。所以这里有两个不同的项目。 查询创建 MySQL 数据库

    CREATE TABLE `users` (
      `id` int(10) unsigned NOT NULL auto_increment,
      `uname` varchar(45) NOT NULL,
      `password` varchar(45) NOT NULL,
      PRIMARY KEY  (`id`)
    );
    
    INSERT INTO `users` (`id`,`uname`,`password`) VALUES
     (1,'admin','123');
    

    注意: 您必须需要将以下两个 jar 放置到项目类路径中。 1.json-simple-1.1.1.jar 2.mysql-connector-java-5.xxx-bin.jar LoginServlet.java

    import dbConnection.DBConnectionHandler;
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.sql.*;
    import java.util.Enumeration;
    import org.json.simple.JSONObject;
    
    public class LoginServlet extends HttpServlet {
    
        // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
        /** 
         * Handles the HTTP <code>GET</code> method.
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            //response.setContentType("text/html;charset=UTF-8");
            JSONObject json = new JSONObject();
    
    
            //ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());
            Enumeration paramNames = request.getParameterNames();
            String params[] = new String[2];
            int i = 0;
            while (paramNames.hasMoreElements()) {
                String paramName = (String) paramNames.nextElement();
    
                //System.out.println(paramName);
                String[] paramValues = request.getParameterValues(paramName);
                params[i] = paramValues[0];
    
                //System.out.println(params[i]);
                i++;
    
            }
    
            String sql = "SELECT uname, password FROM users where uname=? and password=?";
            Connection con = DBConnectionHandler.getConnection();
    
            try {
                PreparedStatement ps = con.prepareStatement(sql);
                ps.setString(1, params[0]);
                ps.setString(2, params[1]);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    json.put("info", "success");
                } else {
                    json.put("info", "fail");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //System.out.println(json);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(json.toString());
        }
    
        /** 
         * Handles the HTTP <code>POST</code> method.
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    DBConnectionHandler.java

    public class DBConnectionHandler {
    
        Connection con = null;
    
        public static Connection getConnection() {
            Connection con = null;
            try {
                Class.forName("com.mysql.jdbc.Driver");//Mysql Connection
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(DBConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname", "root", "pass");//mysql database
    
            } catch (SQLException ex) {
                Logger.getLogger(DBConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
            return con;
        }
    
    }
    

    activity_main.xml

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical"
            android:padding="10dip" >
            <!--  View Title Label -->
            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dip"
                android:text="LOGIN"
                android:textSize="25dip"
                android:textStyle="bold" />
            <!--  User Name Label -->
            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="User Name" />
            <!--  User Name TextField -->
            <EditText
                android:id="@+id/txtUser"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />
    
            <!--  Password Label -->
            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="15dip"
                android:text="Password" />
            <!--  Password TextField -->
            <EditText
                android:id="@+id/txtPass"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:password="true" />
    
            <!--  Login Button -->      
            <Button
                android:id="@+id/button1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dip"
                android:text="Login" />
            </LinearLayout>
    
    </ScrollView>
    

    你可以在这里找到完整的教程和源代码http://www.javaknowledge.info/sample-login-app-in-android-using-servlet-and-json-parsing/

    【讨论】:

    • 非常感谢!我希望有人能指出我正确的方向。我正在查看教程,对于“Servlet 项目”,我可以在 android studio 项目中将其创建为 java 文件吗?
    • 是的,正如我从 "javaknowledge.com" 的博客中读到的,所有文件都在项目 src 文件夹中,首先我建议您阅读我与您分享的教程,按照以下步骤操作然后在你的项目中使用它们。
    • 请记住为此应用程序添加某种安全性。请记住,您不能信任从开放网络获得的请求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    相关资源
    最近更新 更多