Android 开发。。。如何连接到服务器上的mysql数据库

Android 开发。。。如何连接到服务器上的mysql数据库,第1张

1、首先输入代码

public void SendByHttpClient(final String id, final String pw){

new Thread(new Runnable() {

@Override

public void run() {

try {

HttpClient httpclient=new DefaultHttpClient()

HttpPost httpPost=new HttpPost("http://web应用部署服务器上的IP地址:/HttpClientDemo/Login")//服务器地址,指向Servlet

List<NameValuePair>params=new ArrayList<NameValuePair>()//将id和pw装入list

params.add(new BasicNameValuePair("ID",id))

params.add(new BasicNameValuePair("PW",pw))

final UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"utf-8")//以UTF-8格式发送

httpPost.setEntity(entity)

HttpResponse httpResponse= httpclient.execute(httpPost)

if(httpResponse.getStatusLine().getStatusCode()==200)//在200毫秒之内接收到返回值

2、然后再输入下方的代码:

{

HttpEntity entity=httpResponse.getEntity()

String response=EntityUtils.toString(entity1, "utf-8")//以UTF-8格式解析

Message message=new Message()

message.what=USER_LOGIN

message.obj=response

handler.sendMessage(message)使用Message传递消息给线程

}

}

catch (Exception e) {

e.printStackTrace()

}

}

}).start()

  }

3、最终,测试结果图,如下:

用Android程序去直连MySQL数据库,觉得这样做不好,出于安全等方面考虑。数据库地址,用户名密码,查询SQL什么的都存在程序里,很容易被反编译等方法看到。

建议把表示层和数据层逻辑分开,数据层对应网页的表示层提供接口,同时在为Android手机端提供一个接口,简介访问数据库,这接口可以2端都保持一致,比如XML+RPC或者json等等,Android端也有现成的东西能直接用,既安全又省事。

android 链接mysql数据库实例:

package com.hl

import java.sql.DriverManager

import java.sql.ResultSet

import com.mysql.jdbc.Connection

import com.mysql.jdbc.Statement

import android.app.Activity

import android.os.Bundle

import android.view.View

import android.view.View.OnClickListener

import android.widget.Button

import android.widget.TextView

public class AndroidMsql extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState)

setContentView(R.layout.main)

Button btn=(Button)findViewById(R.id.btn)

btn.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

sqlCon()

}

})

}

private void mSetText(String str){

TextView txt=(TextView)findViewById(R.id.txt)

txt.setText(str)

}

private void sqlCon(){

try {

Class.forName("com.mysql.jdbc.Driver")

} catch (Exception e) {

e.printStackTrace()

}

try {

String url ="jdbc:mysql://192.168.142.128:3306/mysql?user=zzfeihua&password=12345&useUnicode=true&characterEncoding=UTF-8"//链接数据库语句

Connection conn= (Connection) DriverManager.getConnection(url)//链接数据库

Statement stmt=(Statement) conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE)

String sql="select * from user"//查询user表语句

ResultSet rs=stmt.executeQuery(sql)//执行查询

StringBuilder str=new StringBuilder()

while(rs.next()){

str.append(rs.getString(1)+"\n")

}

mSetText(str.toString())

rs.close()

Android客户端直接连接远程MySQL数据库的方法如下:

String result = ""

//首先使用NameValuePair封装将要查询的年数和关键字绑定

ArrayList<NameValuePair>nameValuePairs = new ArrayList<NameValuePair>()

nameValuePairs.add(new BasicNameValuePair("year","1980"))

//使用HttpPost封装整个SQL语句

//使用HttpClient发送HttpPost对象

try{

HttpClient httpclient = new DefaultHttpClient()

HttpPost httppost = new HttpPost("http://example.com/getAllPeopleBornAfter.php")

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs))

HttpResponse response = httpclient.execute(httppost)

HttpEntity entity = response.getEntity()

InputStream is = entity.getContent()

}catch(Exception e){

Log.e("log_tag", "Error in http connection "+e.toString())

}

//将HttpEntity转化为String

try{

BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8)

StringBuilder sb = new StringBuilder()

String line = null

while ((line = reader.readLine()) != null) {

sb.append(line + "\n")

}

is.close()

result=sb.toString()

}catch(Exception e){

Log.e("log_tag", "Error converting result "+e.toString())

}

//将String通过JSONArray解析成最终结果

try{

JSONArray jArray = new JSONArray(result)

for(int i=0i<jArray.length()i++){

JSONObject json_data = jArray.getJSONObject(i)

Log.i("log_tag","id: "+json_data.getInt("id")+

", name: "+json_data.getString("name")+

", sex: "+json_data.getInt("sex")+

", birthyear: "+json_data.getInt("birthyear")

)

}

}

}catch(JSONException e){

Log.e("log_tag", "Error parsing data "+e.toString())

}

虽然Android开发中可以直接连接数据库,但是实际中却不建议这么做,应该使用服务器端中转下完成。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/6110731.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-15
下一篇 2023-03-15

发表评论

登录后才能评论

评论列表(0条)

保存