有點多請耐心看完。
希望能幫助你,還請及時採納謝謝。
一.前言
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
㈡ android 如何連接mysql資料庫,並且往資料庫裡面插入數據
1.首先需要安裝MySQL Server 5.1和navicat for mysql。這個安裝是很簡單的,網上很多教程,和安裝一般軟體差不多。只有在安裝MySQL Server 5.1時,要注意選擇字元編碼為gb2312(中文)那個選項。
2. 使用navicat for mysql導入數據文件
a打開navicat for mysql,和localhost本地資料庫連接,就可以看到剛才建立的資料庫和表,
b可以導入本地的txt數據文件,注意保持格式正確,
c下面一步要注意一下,如果資料庫中有中文數據,編碼格式一定要選擇是中文的GB2312,
d然後間隔符為空格(根據txt中的具體情況來定),
e並選擇目標表,將每一列一一對應,即可導入。
㈢ 安卓app 怎麼連接mysql
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();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
不過eclipse老是提示:
warning: Ignoring InnerClasses attribute for an anonymous inner class that doesn't come with an associated EnclosingMethod attribute. (This class was probably proced by a broken compiler.)
㈣ android怎麼連接mysql資料庫
用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();
㈤ 安卓怎麼連接mysql資料庫數據
現在不能直接連接,不過你可以再寫一個web伺服器端,通過java網路編程遠程訪問,web伺服器端返回xml數據再解析。這樣即使換了別的非android客戶端,也容易移植。
㈥ 跪求android大神 怎麼將mysql資料庫連接到eclipse編寫的安卓應用中
1.前邊的事例是把資料庫的驅動,連接,用戶名和密碼都寫在了類中,耦合性太高,當我們資料庫變更或者資料庫類型更換後,需要去重新更改代碼,很不方便。
解決的方法:把資料庫的驅動,連接,用戶名和密碼寫在配置文件中,通過讀取配置文件的方式進行代碼編寫,而以後如果資料庫變更直接修改配置文件即可!
2.在工程中右鍵新建file,命名為jdbc.properties
3.創建完畢如圖:
4.在jdbc.properties文件中輸入如下信息,分別是資料庫的驅動,連接,用戶名和密碼
5.新建JdbcTest2.java類
6.輸入自己的代碼:
7.在主函數中輸入如下,測試方法
8.運行之後的結果如下,表示連接成功!
㈦ 請問Android怎樣連接遠程MySQL資料庫
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=0;i<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開發中可以直接連接資料庫,但是實際中卻不建議這么做,應該使用伺服器端中轉下完成。
㈧ 火山安卓連接不上mysql 但是navicat能連接成功
解決Navicat無法連接到MySQL的問題
解決Navicat無法連接到MySQL的問題
問題一:本地IP(xxx.xxx.xxx.xxx)沒有訪問遠程資料庫的許可權。於是下面開啟本地IP(xxx.xxx.xxx.xxx)對遠程mysql資料庫的訪問許可權。
這里開啟許可權,要在遠程資料庫伺服器上開:
解決辦法:
1、首先在遠程伺服器上連接進入mysql,在cmd中輸入mysql -u root -p,然後回車,輸入密碼後回車進入mysql命令行。
2、輸入下面命令,授權所有的客戶端都可以訪問伺服器的許可權,下面的『123456』為你資料庫的實際密碼,記得修改:
grant all privileges on *.* to root@'%' identified by '123456';
3、輸入下面命令,刷新許可權
flush privileges;
4、進入相應目錄修改ssh_config和sshd_config文件
cd /etc/ssh
vi ssh_config
將 #PasswordAuthentication yes改為PasswordAuthentication yes,我們去掉了它前面的#
編輯sshd_config 做同樣的去掉『#』操作
5、然後重新啟動mysql服務
/etc/init.d/mysqld restart
這里如果加入了服務,就直接可以用service。