手机连接MySql数据库

     近期在学习注册与记录方面的应用,主要功能是:在手机端进行信息注册,注册完成后自动把信息写入到服务器端数据库中。

      本方案实现手机连接PC端MySql数据库的基本思路是:手机和PC端建立TCP连接,通过TCP连接实现对数据库操作命令(比如增删改查)的 传递,并将操作结果反馈给手机端。

手机端代码:

SignActivity.java

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SignActivity extends Activity {

	private Button sign;
	private EditText name;
	private EditText number;
	private EditText rfid;
	private final String IP="202.118.16.129";
	private final int PORT=6363;
	Socket socket=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		initView();
		sign.setOnClickListener(new MyClickListener());
		
	}
	
	private void initView(){
		sign=(Button) findViewById(R.id.sign_bt);
		name=(EditText) findViewById(R.id.name_et);
		number=(EditText) findViewById(R.id.telephone_et);
		rfid=(EditText) findViewById(R.id.rfid_et);
		rfid.setText(getIntent().getStringExtra("rfid"));
	}
	/**
	 * 监听注册事件
	 * @author 
	 *
	 */
	class MyClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch(v.getId()){
			case R.id.sign_bt:
				if(isInputRight()){
				   new SubmitThread().start();		
				}
						
				break;
			}
			
		}
	/**
	 * 判断输入是否合法。	
	 * @return
	 */
	private boolean isInputRight(){
		String tempName=name.getText().toString().trim();
		String tempNumber=number.getText().toString().trim();
		if(tempName.isEmpty()||tempNumber.isEmpty()){
			Toast.makeText(SignActivity.this, "用户名和手机号不能为空!", Toast.LENGTH_SHORT).show();
			return false;
		}
		if(tempNumber.length()!=11)	{
			Toast.makeText(SignActivity.this, "您输入的手机号有误,请仔细检查!", Toast.LENGTH_SHORT).show();
			return false;
		}
			
		return true;
		
	}
		

	}

	/**
	 * TCP socket通讯线程
	 * @author 
	 *
	 */
	class SubmitThread extends Thread{

		@Override
		public void run() {
			try{
			socket=new Socket(IP,PORT);
			BufferedWriter writeMSG=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8"));			
			String send=name.getText().toString().trim()+","+number.getText().toString().trim()+"\n";
			Log.e("发送",send);
			
			writeMSG.write(send);
			writeMSG.flush();
			}
			catch(Exception e){
				e.printStackTrace();
			}finally{
				//writeMSG.close();
				if(socket!=null)
					try {
						socket.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
			
			
		}
		
	}
	
	
}
界面布局文件activity_main.xml



   
      
        
        
    
    
      
        
        
    
    
    
      
              
    
    
界面效果(示意):

手机连接MySql数据库_第1张图片


PC端主要的功能是接收手机端发来的数据,并连接数据库进行操作。

主要代码为:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import java.sql.*;

	public class Server {
	 static ServerSocket aServerSocket = null; // Server Socet.
	 DataInputStream aDataInput = null; // 输入流,接收来自客户端的数据
	 DataOutputStream aDataOutput = null; // 输出流,写到
	 BufferedWriter writer=null;
	 BufferedReader reader=null;
	 
	 static ArrayList list = new ArrayList();//连接列表,静态变量,全局唯一
	 
	 public static void insert_to_sql(String name,String num){
		 
		 try {
			    String sql="insert into why values('"+name+"','"+num+"')";
				//Connection connect =DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/sign?user=名称&password=密码");
				// 连接URL为 jdbc:mysql//服务器地址/数据库	名 ,后面的2个参数分别是登陆用户名和密码
				Connection connect =DriverManager.getConnection("jdbc:mysql://202.118.16.129:3306/mtest?user=名称&password=密码");
				System.out.println("Success connect Mysql server!");
				Statement stmt = connect.createStatement();				
				stmt.executeUpdate(sql);
				ResultSet rs = stmt.executeQuery("select * from why");

				while (rs.next()) {
					System.out.println(rs.getString("name"));
					System.out.println(rs.getString("year"));
		
				}
				stmt.close();
				rs.close();
			} catch (Exception e) {
				System.out.print("get data error!");
				e.printStackTrace();
			}
		 	 	 
	 }
	 public static void main(String[] args) {
				
		 
			try {
				Class.forName("com.mysql.jdbc.Driver"); // 加载MYSQL JDBC驱动程序
				System.out.println("Success loading Mysql Driver!");
			} catch (Exception e) {
				System.out.print("Error loading Mysql Driver!");
				e.printStackTrace();
			}
			
			insert_to_sql("小强","1992-09-23");
			 
	  try {
	      aServerSocket = new ServerSocket(6363); // 监听端口
	      System.out.println("already listen 1025 port.");
	  } catch (Exception e) {
	      e.printStackTrace();
	  }
	
	  while (true {
	   Socket aSessionSoket = null;
	   try {
	    aSessionSoket = aServerSocket.accept();//阻塞,监听连接请求
	    System.out.println("jianlilianjie");//建立一个连接,则开启一个处理线程
	    MyThread thread = new Server().new MyThread(aSessionSoket);
	    thread.start();//开启线程进行数据传输处理
	    System.out.println("开启了一个线程");
	 
	   } catch (IOException e1) {
	    // TODO Auto-generated catch block
	    e1.printStackTrace();
	   }
	  }
	 }

	  class MyThread extends Thread {
	  Socket aSessionSoket = null;

	  public MyThread(Socket socket) {
	   aSessionSoket = socket;
	  }

	  public void run() {
	   try {
	//一、获取缓冲流------------------------------
		System.out.println("jianlilianjie2");
	    
	       aDataInput = new DataInputStream(aSessionSoket.getInputStream());
	       aDataOutput = new DataOutputStream(aSessionSoket.getOutputStream());
	       
	       writer=new BufferedWriter(new OutputStreamWriter(aDataOutput, "UTF-8"));
	       reader=new BufferedReader(new InputStreamReader(aDataInput, "UTF-8"));
	       
	       System.out.println("jianlilianjie3");
	       list.add(writer);    
	       
	//二、读写数据---------------把读进来的数据写到数据库。
	       
	    while (true) {
	              
	     String msg = reader.readLine();  //读一行数据
	          	            
	     if (msg!=null) {
	    	 String []tempMsg=msg.split(",");  
	    	 insert_to_sql(tempMsg[0],tempMsg[1]); 
	         System.out.println("ip: "+ aSessionSoket.getInetAddress());// ip.
	         System.out.println("receive msg: " + msg);
	      
	     }
	    }

	   } catch (IOException e) {	  
	     e.printStackTrace();
	   } finally {
	    try {
	    	reader.close();
	     if (writer != null)
	    	 writer.close();
	     list.remove(writer);
	     aSessionSoket.close();

	    } catch (Exception e2) {
	     e2.printStackTrace();
	    }
	   }
	  }
	 }
       }

注意事项:

1.BufferedReader和BufferedWriter发送接收汉字乱码的解决办法:指定相同的编码格式。如:

BufferedWriter  writer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));

BufferedReader  reader=new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));

2.连接远程数据库时,需要数据库授权才能连接成功。

3.不重复插入数据,示例: 

     String str2= "INSERT INTO why (name, year) SELECT '小明', '1992-12-22' FROM dual WHERE NOT EXISTS (SELECT * FROM 
     why WHERE name = '小明' AND year = '1992-12-23' )";





你可能感兴趣的:(Android学习笔记,手机连接数据库,MySql)