導航:首頁 > 操作系統 > androidmysql驅動

androidmysql驅動

發布時間:2024-05-08 08:44:45

1. 怎樣使android程序調用mysql資料庫裡面的數據

一、首先要載入JDBC驅動包。

步驟:右擊項目找到build path->configure build path->libraries——>add External JARs添加驅動包

二、寫測試類:TestCon.java

(在此之前,首先

1.在自己的電腦上Mysql下確定賬戶是"root",密碼是"123456";

2.進入賬戶,創建資料庫cui;

3.在資料庫cui下面,創建表test1 包含_id(int 類型自動增加) username(String 類型)、password(String 類型);

4.在表中插入數據,以便顯示



1 package com.test.an;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.PreparedStatement;
6 import java.sql.ResultSet;
7 import java.sql.SQLException;
8
9
10 public class TestCon1{
11 public static void main(String[] args)
12 {
13 Connection con = null;
14 String sql;
15 PreparedStatement pre;
16 ResultSet rs;
17
18 try {
19 String driver="com.mysql.jdbc.Driver";
20 Class.forName(driver);
21
22 String url="jdbc:mysql://localhost:3306/cuiuseUnicode=true&characterEncoding=latin1";//utf-8也行
23 con = DriverManager.getConnection(url, "root", "123456");
24
25 sql = "select _id,username,password from test1" ;
26 pre = con.prepareStatement(sql);
27
28 rs = pre.executeQuery();
29 while(rs.next()){
30 int id = rs.getInt(1);
31 String username = rs.getString(2);
32 String password = rs.getString(3);
33
34 System.out.println("id="+id+";username="+username+";password="+password);
35 }
36 con.close();
37 } catch (SQLException e) {
38 e.printStackTrace();
39 } catch (ClassNotFoundException e) {
40 e.printStackTrace();
41 }
42
43 }
44
45 }
運行結果:

id=1;username=ccc;password=123456
id=2;username=xxx;password=654321
id=3;username=ddd;password=123456
id=4;username=ddf÷;password=yyt
id=5;username=cuixiaodong;password=cxd
id=6;username=vv;password=cxd

2. android怎麼鏈接資料庫mysql

有點多請耐心看完。
希望能幫助你,還請及時採納謝謝。
一.前言

android連接資料庫的方式有兩種,第一種是通過連接伺服器,再由伺服器讀取資料庫來實現數據的增刪改查,這也是我們常用的方式。第二種方式是android直接連接資料庫,這種方式非常耗手機內存,而且容易被反編譯造成安全隱患,所以在實際項目中不推薦使用。

二.准備工作

1.載入外部jar包

在Android工程中要使用jdbc的話,要導入jdbc的外部jar包,因為在Java的jdk中並沒有jdbc的api,我使用的jar包是mysql-connector-java-5.1.18-bin.jar包,網路上有使用mysql-connector-java-5.1.18-bin.jar包的,自己去用的時候發現不兼容,所以下載了比較新版本的,jar包可以去官網下載,也可以去網路,有很多前人們上傳的。

2.導入jar包的方式

方式一:

可以在項目的build.gradle文件中直接添加如下語句導入

compile files('libs/mysql-connector-java-5.1.18-bin.jar')
方式二:下載jar包復制到項目的libs目錄下,然後右鍵復制過來的jar包Add as libs

三.建立資料庫連接

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jdbc);
new Thread(runnable).start();
}

Handler myHandler=new Handler(){

public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
Bundle data=new Bundle();
data=msg.getData();

//System.out.println("id:"+data.get("id").toString()); //輸出第n行,列名為「id」的值
Log.e("TAG","id:"+data.get("id").toString());
TextView tv= (TextView) findViewById(R.id.jdbc);

//System.out.println("content:"+data.get("content").toString());
}
};

Runnable runnable=new Runnable() {
private Connection con = null;

@Override
public void run() {
// TODO Auto-generated method stub
try {
Class.forName("com.mysql.jdbc.Driver");
//引用代碼此處需要修改,address為數據IP,Port為埠號,DBName為數據名稱,UserName為資料庫登錄賬戶,Password為資料庫登錄密碼
con =
//DriverManager.getConnection("jdbc:mysql://192.168.1.202:3306/b2b", "root", "");
DriverManager.getConnection("jdbc:mysql://http://192.168.1.100/phpmyadmin/index.php:8086/b2b",
UserName,Password);

} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

try {
testConnection(con); //測試資料庫連接
} catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void testConnection(Connection con1) throws java.sql.SQLException {
try {
String sql = "select * from ecs_users"; //查詢表名為「oner_alarm」的所有內容
Statement stmt = con1.createStatement(); //創建Statement
ResultSet rs = stmt.executeQuery(sql); //ResultSet類似Cursor

//<code>ResultSet</code>最初指向第一行
Bundle bundle=new Bundle();
while (rs.next()) {
bundle.clear();
bundle.putString("id",rs.getString("userid"));
//bundle.putString("content",rs.getString("content"));
Message msg=new Message();
msg.setData(bundle);
myHandler.sendMessage(msg);
}

rs.close();
stmt.close();
} catch (SQLException e) {

} finally {
if (con1 != null)
try {
con1.close();
} catch (SQLException e) {}
}
}
};

注意:

在Android4.0之後,不允許在主線程中進行比較耗時的操作(連接資料庫就屬於比較耗時的操作),需要開一個新的線程來處理這種耗時的操作,沒新線程時,一直就是程序直接退出,開了一個新線程處理直接,就沒問題了。

當然,連接資料庫是需要網路的,千萬別忘了添加訪問網路許可權:

<uses-permission android:name=」android.permission.INTERNET」/>

四.bug點

1.導入的jar包一定要正確

2.連接資料庫一定要開啟新線程

3.資料庫的IP一定要是可以ping通的,區域網地址手機是訪問不了的

4.資料庫所在的伺服器是否開了防火牆,阻止了訪問
————————————————
版權聲明:本文為CSDN博主「shuaiyou_comon」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/shuaiyou_comon/article/details/75647355

3. android 連接mysql資料庫問題

我也是初學,給你參考一下
tomcat伺服器端:
public class LoginOrRegServlet extends HttpServlet { //登錄和注冊伺服器
private static final long serialVersionUID = 1L;
private static final String Driver = "com.mysql.jdbc.Driver"; //mysql驅動
private static final String ConnectUrl = "jdbc:MySQL://localhost:3306/itosystem";//連接資料庫的URL
private String User = "root"; //登錄資料庫的用戶名和密碼
private String Password = "num12369";
@Override
protected void service(HttpServletRequest request,HttpServletResponse response) { String connUserName; //取得請求中的用戶名和密碼
String connPassword;
String Action; //判斷請求中是登錄還是注冊
boolean isNull = false; //根據用戶名查詢資料庫是否查到
Connection conn = null;
DataOutputStream dos = null;
Statement statement = null;
ResultSet rs = null;
connUserName = request.getParameter("userName");//取得請求中的各種值
connPassword = request.getParameter("password");
Action = request.getParameter("action");
System.out.println(connUserName + "-" + connPassword+"-"+Action);
try { //設置驅動和連接資料庫
Class.forName(Driver);
conn = DriverManager.getConnection(ConnectUrl, User, Password);
} catch (Exception e1) {
e1.printStackTrace();
}
if(Action.equals("reg")){ //if請求為注冊
try {
if (conn != null) { //if資料庫連接成功

statement = conn.createStatement(); //取得對資料庫的操作對象
rs = statement.executeQuery("select password from user where name='"
+ connUserName + "'"); //根據請求中的用戶名使用mysql語句對資料庫的查詢操作
dos = new DataOutputStream(response.getOutputStream()); //對請求做出回應的對象
if(!rs.next()){ //如果沒有查到記錄,表明用戶名可以使用
statement.executeUpdate("insert into user values('"+connUserName+"','"+connPassword+"')");
//執行插入操作
dos.writeInt(5); //回應給客戶端的值(值可以隨意),5表示成功
}else{
dos.writeInt(10); //10表示用戶已存在
}
dos.flush(); //關閉各種對象
dos.close();
rs.close();
statement.close();
conn.close();
}else{
System.out.println("資料庫連接失敗");
}
} catch (Exception e) {
System.out.println("產生異常");
e.printStackTrace();
}
//注冊結束
}else if(Action.equals("login")){//if請求為登錄
try {
if (conn != null) {
statement = conn.createStatement();
rs = statement.executeQuery("select password from user where name='"+ connUserName + "'"); //查詢資料庫
dos = new DataOutputStream(response.getOutputStream());
while(rs.next()){//if查詢到有這個用戶名的記錄
String backPassword;
backPassword = rs.getString("password"); //從資料庫獲得這個用戶名的密碼
if (backPassword.equals(connPassword)) { //用資料庫返回的密碼和連接請求中的密碼對比
dos.writeInt(10); //如果相等,返回值,登錄成功
}else{
dos.writeInt(0); //否則登錄失敗
}
isNull = true; //查到有記錄,將其賦值為true
}
if(!isNull){ //if沒查到記錄
dos.writeInt(5); //返回5,表示用戶不存在
}
dos.flush(); //關閉各種對象
dos.close();
rs.close();
statement.close();
conn.close();
} else {
System.out.println("資料庫連接失敗");
}
} catch (Exception e) {
e.printStackTrace();

}
}
}//登錄操作結束
}

4. android鎬庝箞榪炴帴mysql

璇磋存柟娉曞惂銆侫ndroid寮鍙戜腑錛屽ぇ澶氭暟榪炴帴鍒拌繙紼婱ySQL鏁版嵁搴撶殑鏂規硶鏄鍔犲叆鐗瑰畾鐨凷ervice鍒頒唬鐮佷腑銆傜敱浜嶮ySQL閫氬父鏄鍜孭HP涓璧蜂嬌鐢ㄧ殑錛屾渶綆鍗曚互鍙婃渶甯歌佺殑鏂規硶鏄鍐橮HP鑴氭湰綆$悊鏁版嵁榪炴帴錛屼互鍙婁粠Android緋葷粺涓婁嬌鐢℉TTP鍗忚榪愯岃繖涓鑴氭湰銆

5. 怎麼連接android和php mysql資料庫

如何連接android和php mysql資料庫

我們先來看一個簡單的Android app例子(這里是一個商品存貨清單項目),在Android程序中,我們可以訪問(call)PHP腳本來執行簡單的CRUD操作(創建,讀取,更新,刪除)。為了使你對它的體系結構有一個大概的了解,這里先說一下它是怎麼工作的。首先你的Android項目訪問(call)PHP腳本來執行一條數據操作,我們稱它為「創建」。然後PHP腳本連接MySQL資料庫來執行這個操作。這樣,數據從Android程序流向PHP腳本,最終存儲在MySQL資料庫中。
好了,讓我們來深入的看一下。
請注意:這里提供的代碼只是為了使你能簡單的連接Android項目和PHP,MySQL。你不能把它作為一個標准或者安全編程實踐。在生產環境中,理想情況下你需要避免使用任何可能造成潛在注入漏洞的代碼(比如MYSQL注入)。MYSQL注入是一個很大的話題,不可能用單獨的一篇文章來說清楚,並且它也不在本文討論的范圍內,所以本文不以討論。
1. 什麼是WAMP Server
WAMP是Windows,Apache,MySQL和PHP,Perl,Python的簡稱。WAMP是一個一鍵安裝的軟體,它為開發PHP,MySQL Web應用程序提供一個環境。安裝這款軟體你相當於安裝了Apache,MySQL和PHP。或者,你也可以使用XAMP。

2. 安裝和使用WAMP Server
你可以從http://www.wampserver.com/en/下載WAMP,安裝完成之後,可以從開始->所有程序->WampServer->StartWampServer運行該程序。
在瀏覽器中輸入http://localhost/來測試你的伺服器是否安裝成功。同樣的,也可以打開http://localhost/phpmyadmin來檢驗phpmyadmin是否安裝成功。
3. 創建和運行PHP項目
現在,你已經有一個能開發PHP和MYSQL項目的環境了。打開安裝WAMP Server的文件夾(在我的電腦中,是C:\wamp\),打開www文件夾,為你的項目創建一個新的文件夾。你必須把項目中所有的文件放到這個文件夾中。
新建一個名為android_connect的文件夾,並新建一個php文件,命名為test.php,嘗試輸入一些簡單的php代碼(如下所示)。輸入下面的代碼後,打開http://localhost/android_connect/test.php,你會在瀏覽器中看到「Welcome,I am connecting Android to PHP,MySQL」(如果沒有正確輸入,請檢查WAMP配置是否正確)
test.php

4. 打開MainScreenActivity.java為main_screen.xml文件里的兩個按鈕添加點擊事件

MainScreenActivity.java

7. 添加一個新產品(寫入)
創建一個新的view和activity來向MySQL資料庫添加新產品。
新建一個簡單的表單,創建提供輸入產品名稱,價格和描述的EditText
add_proct.xml

8. 新建一個Activity來處理向MySQL資料庫插入新產品。
新建名為NewProctActivity.java的文件,輸入以下代碼。在下面的代碼中
首先,從EditText獲得用戶輸入的產品數據,格式化成基本參數格式
然後,向create_proct.php發送請求,通過HTTP POST創建一個新的產品
最後,從create_proct.php獲取json返回值,如果success值為1,新得到的列表中就加入了新增的產品。
NewProctActivity.java

11. JSONParser類
我用一個JSONParser類從URL獲得JSON格式的數據。這個類支持兩種http請求,GET和POST方法從URL獲取JSON數據
JSONParser.java

packagecom.example.androidhive; importjava.io.BufferedReader; importjava.io.IOException; importjava.io.InputStream; importjava.io.InputStreamReader; importjava.io.UnsupportedEncodingException; importjava.util.List; importorg.apache.http.HttpEntity; importorg.apache.http.HttpResponse; importorg.apache.http.NameValuePair; importorg.apache.http.client.ClientProtocolException; importorg.apache.http.client.entity.UrlEncodedFormEntity; importorg.apache.http.client.methods.HttpGet; importorg.apache.http.client.methods.HttpPost; importorg.apache.http.client.utils.URLEncodedUtils; importorg.apache.http.impl.client.DefaultHttpClient; importorg.json.JSONException; importorg.json.JSONObject; importandroid.util.Log; publicclassJSONParser { staticInputStream is = null; staticJSONObject jObj = null; staticString json = ""; // constructor publicJSONParser() { } // function get json from url // by making HTTP POST or GET mehtod publicJSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) { // Making HTTP request try{ // check for request method if(method == "POST"){ // request method is POST // defaultHttpClient DefaultHttpClient httpClient = newDefaultHttpClient(); HttpPost httpPost = newHttpPost(url); httpPost.setEntity(newUrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); }elseif(method == "GET"){ // request method is GET DefaultHttpClient httpClient = newDefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?"+ paramString; HttpGet httpGet = newHttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch(UnsupportedEncodingException e) { e.printStackTrace(); } catch(ClientProtocolException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } try{ BufferedReader reader = newBufferedReader(newInputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = newStringBuilder(); String line = null; while((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch(Exception e) { Log.e("Buffer Error", "Error converting result "+ e.toString()); } // try parse the string to a JSON object try{ jObj = newJSONObject(json); } catch(JSONException e) { Log.e("JSON Parser", "Error parsing data "+ e.toString()); } // return JSON String returnjObj; } }
到這里,本教程就結束了。

6. 怎樣使Android程序調用mysql資料庫裡面的數據

1.首先需要安裝MySQLServer5.1和navicatformysql。這個安裝是很簡單的,網上很多教程,和安裝一般軟體差不多。只有在安裝MySQLServer5.1時,要注意選擇字元編碼為gb2312(中文)那個選項。

2.使用navicatformysql導入數據文件
a打開navicatformysql,和localhost本地資料庫連接,就可以看到剛才建立的資料庫和表,
b可以導入本地的txt數據文件,注意保持格式正確,
c下面一步要注意一下,如果資料庫中有中文數據,編碼格式一定要選擇是中文的GB2312,
d然後間隔符為空格(根據txt中的具體情況來定),
e並選擇目標表,將每一列一一對應,即可導入。

閱讀全文

與androidmysql驅動相關的資料

熱點內容
qtdesignerlinux 瀏覽:429
命令的幾要素 瀏覽:932
代理伺服器地址怎麼知道 瀏覽:170
漢語命令形 瀏覽:193
ACG官網下載的游戲怎麼解壓 瀏覽:963
stata交叉項命令 瀏覽:470
程序員老公燙頭 瀏覽:692
伺服器文件地址格式 瀏覽:131
securecrtandroid 瀏覽:176
短字元串壓縮 瀏覽:863
u盤插入後顯示加密格式化 瀏覽:944
我的世界怎麼用命令方塊獲得超級武器 瀏覽:382
狗語翻譯器app鏈接怎麼下 瀏覽:905
選擇排序演算法的流程圖 瀏覽:881
如何對文件夾開啟共享 瀏覽:527
常用的磁碟調度演算法 瀏覽:662
怎麼用返利app返利 瀏覽:127
java代碼快速 瀏覽:243
單片機左移右移後是補1還是0 瀏覽:599
湛江一號命令 瀏覽:333