當前位置:首頁 » 數據倉庫 » android連接資料庫代碼
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

android連接資料庫代碼

發布時間: 2022-11-26 03:28:33

⑴ Android studio怎麼連接本地資料庫設計登錄界面

我們項目的前提是你已經將基本的運行環境及sdk都已經安裝好了,讀者可自行網路環境配置相關內容,本文不再贅述。右鍵點擊new-->Mole,Mole相當於新建了一個項目。

選擇Android Application,點擊next

將My Mole 和app改成自己項目相應的名字,同時選擇支持的Android版本

這一步我們選擇Blank Activity,自己手動編寫登錄界面,而不依賴系統內置的Login Activity,一直點擊next,最後點擊finish就完成了項目的創建

在project下我們可以看到出現了我們剛才創建的login項目

展開res/layout,點擊打開activity_main.xml文件,在這個文件里我們將完成登錄界面的編寫

這是初始的主界面,還沒有經過我們編寫的界面,Android Studio有一個很強大的預覽功能,相當給力,將activity_main.xml的代碼替換成如下代碼:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:stretchColumns="0,3">
<TableRow>
<TextView />
<TextView
android:text="賬 號:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24px"
/>
<EditText

⑵ 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();

⑶ Android 開發。。。如何連接到伺服器上的mysql資料庫

1、打開Tableau軟體。

⑷ android怎麼連接sqlite資料庫

SQLite 一個非常流行的嵌入式資料庫,它支持 SQL 語言,並且只利用很少的內存就有很好的性能。此外它還是開源的,任何人都可以使用它。許多開源項目((Mozilla, PHP, Python)都使用了 SQLite.

Android 開發中使用 SQLite 資料庫
Activites 可以通過 Content Provider 或者 Service 訪問一個資料庫。下面會詳細講解如果創建資料庫,添加數據和查詢資料庫。
創建資料庫
Android 不自動提供資料庫。在 Android 應用程序中使用 SQLite,必須自己創建資料庫,然後創建表、索引,填充數據。Android 提供了 SQLiteOpenHelper 幫助你創建一個資料庫,你只要繼承 SQLiteOpenHelper 類,就可以輕松的創建資料庫。SQLiteOpenHelper 類根據開發應用程序的需要,封裝了創建和更新資料庫使用的邏輯。SQLiteOpenHelper 的子類,至少需要實現三個方法:
構造函數,調用父類 SQLiteOpenHelper 的構造函數。這個方法需要四個參數:上下文環境(例如,一個 Activity),資料庫名字,一個可選的游標工廠(通常是 Null),一個代表你正在使用的資料庫模型版本的整數。
onCreate()方法,它需要一個 SQLiteDatabase 對象作為參數,根據需要對這個對象填充表和初始化數據。
onUpgrage() 方法,它需要三個參數,一個 SQLiteDatabase 對象,一個舊的版本號和一個新的版本號,這樣你就可以清楚如何把一個資料庫從舊的模型轉變到新的模型。

⑸ android 如何連接資料庫

這種方式通常連接一個外部的資料庫,第一個參數就是資料庫文件,這個資料庫不是當前項目中生成的,通常放在項目的Assets目錄下,當然也可以在手機內,如上面參數那個目錄,前提是那個文件存在且你的程序有訪問許可權。

另一種使用資料庫的方式是,自己創建資料庫並創建相應的資料庫表,參考下面的代碼:
public class DatabaseHelper extends SQLiteOpenHelper {
//構造,調用父類構造,資料庫名字,版本號(傳入更大的版本號可以讓資料庫升級,onUpgrade被調用)
public DatabaseHelper(Context context) {
super(context, DatabaseConstant.DATABASE_NAME, null, DatabaseConstant.DATABASE_VERSION);
}
//資料庫創建時調用,裡面執行表創建語句.
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createVoucherTable());
}
//資料庫升級時調用,先刪除舊表,在調用onCreate創建表.
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DatabaseConstant.TABLE_NAME);
onCreate(db);
}
//生成 創建表的SQL語句
private String createVoucherTable() {
StringBuffer sb = new StringBuffer();
sb.append(" CREATE TABLE ").append(DatabaseConstant.TABLE_NAME).append("( ").append(「ID」)
.append(" TEXT PRIMARY KEY, ")
.append(「USER_ID」).append(" INTEGER, ").append(「SMS_CONTENT」).append(" TEXT ) ");
return sb.toString();
}
} 繼承SQLiteOpenHelper並實現裡面的方法.

之後:
//得到資料庫助手類
helper
=
new
DatabaseHelper(context);
//通過助手類,打開一個可讀寫的資料庫連接
SQLiteDatabase
database
=
helper.getReadableDatabase();
//查詢表中所有記錄
database.query(DatabaseConstant.TABLE_NAME,
null,
null,
null,
null,
null,
null);

⑹ android怎麼連接sqlite資料庫

Android連接SQLite資料庫
1、DatabaseHelper類繼承了SQLiteOpenHelper類,並重寫了onCreate和onUngrade方法。
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper (Context context){
Super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db){
String sql = "CREATE TABLE tb_test (_id INTEGER DEFAULT '1' NOT NULL PRIMARY KEY AUTOINCREMENT,class_jb TEXT NOT NULL,class_ysbj TEXT NOT NULL,title TEXT NOT NULL,content_ysbj TEXT NOT NULL)"; }
db.execSQL(sql);
}
public void onUpgrade (SQLiteDatabase db,int oldVersion,int newVersion){
}
}
1、SQLiteOpenHelper (android.database.sqlite.SQLiteOpenHelper)
這是一個抽象類,關於抽象類我們都知道,如果要使用它,一定是繼承它!
這個類的方法很少,有一個構造方法
SQLiteOpenHelper(android.content.Context context, java.lang.String name,android.database.sqlite.SQLiteDatabase.CursorFactory factory, int version);
參數不做過多的解釋,CursorFactory一般直接傳null就可以
public void onCreate(SQLiteDatabase db)
此方法在創建資料庫是被調用,所以,應該把創建表的操作放到這個方法裡面,一會兒在後面我們會再詳細的說如何創建表
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
從方法名上我們就能知道這個方法是執行更新的,沒錯,當version改變是系統會調用這個方法,所以在這個方法里應該執行刪除現有表,然後手動調用onCreate的操作
SQLiteDatabase getReadableDatabase()
可讀的SQLiteDatabase對象
SQLiteDatabase getWritableDatabase()
獲取可寫的SQLiteDatabase對象
2、SQLiteDatabase(android.database.sqlite.SQLiteDatabase)
關於操作資料庫的工作(增、刪、查、改)都在這個類里
execSQL(sql)
執行SQL語句,用這個方法+SQL語句可以非常方便的執行增、刪、查、改.除此之外,Android還提供了功過方法實現增、刪、查、改
long insert(TABLE_NAME, null, contentValues)添加記錄
int delete(TABLE_NAME, where, whereValue)刪除記錄
int update(TABLE_NAME, contentValues, where, whereValue) 更新記錄
Cursor query(TABLE_NAME, null, null, null, null, null, null) 查詢記錄
除此之外,還有很多方法,如:beginTransaction()開始事務、endTransaction()結束事務...有興趣的可以自己看api,這里就不多贅述了
3、Cursor(android.database.Cursor)
游標(介面),這個很熟悉了吧,Cursor里的方法非常多,常用的有:
boolean moveToPosition(position)將指針移動到某記錄
getColumnIndex(Contacts.People.NAME)按列名獲取id
int getCount()獲取記錄總數
boolean requery()重新查詢
boolean isAfterLast()指針是否在末尾
boolean isBeforeFirst()時候是開始位置
boolean isFirst()是否是第一條記錄
boolean isLast()是否是最後一條記錄
boolean moveToFirst()、 boolean moveToLast()、 boolean moveToNext()同moveToPosition(position)
4、SimpleCursorAdapter(android.widget.SimpleCursorAdapter)
也許你會奇怪了,之前我還說過關於資料庫的操作都在database和database.sqlite包下,為什麼把一個Adapter放到這里,如果你用過Android的SQLite3,你一定會知道,這是因為我們對資料庫的操作會經常跟列表聯系起來經常有朋友會在這出錯,但其實也很簡單
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.list,myCursor,new String[] {DB.TEXT1,DB. TEXT2},new int[]{ R.id.list1,R.id.listText2 });my.setAdapter(adapter);
一共5個參數,具體如下:
參數1:Content
參數2:布局
參數3:Cursor游標對象
參數4:顯示的欄位,傳入String[]
參數5:顯示欄位使用的組件,傳入int[],該數組中是TextView組件的id

一、寫一個類繼承SQLiteOpenHelpe
public class DatabaseHelper extends SQLiteOpenHelper
構造方法:
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
在onCreate方法里寫建表的操作
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE tb_test (_id INTEGER DEFAULT '1' NOT NULL PRIMARY KEY AUTOINCREMENT,class_jb TEXT NOT NULL,class_ysbj TEXT NOT NULL,title TEXT NOT NULL,content_ysbj TEXT NOT NULL)";
db.execSQL(sql);//需要異常捕獲
}
在onUpgrade方法里刪除現有表,然後手動調用onCtreate創建表
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "drop table "+tbname;
db.execSQL(sql);
onCreate(db);
}
對表增、刪、查、改的方法,這里用的是SQLiteOpenHelper提供的方法,也可以用sql語句實現,都是一樣的
關於獲取可讀/可寫SQLiteDatabase,我不說大家也應該會想到,只有查找才會用到可讀的SQLiteDatabase
public long insert(String tname, int tage, String ttel){
SQLiteDatabase db= getWritableDatabase();//獲取可寫SQLiteDatabase對象
//ContentValues類似map,存入的是鍵值對
ContentValues contentValues = new ContentValues();
contentValues.put("tname", tname);
contentValues.put("tage", tage);
contentValues.put("ttel", ttel);
return db.insert(tbname, null, contentValues);
}
public void delete(String _id){
SQLiteDatabase db= getWritableDatabase();
db.delete(tbname,
"_id=?",
new String[]{_id});
}
public void update(String _id,String tname, int tage, String ttel){
SQLiteDatabase db= getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("tname", tname);
contentValues.put("tage", tage);
contentValues.put("ttel", ttel);
db.update(tbname, contentValues,
"_id=?",
new String[]{_id});
}
public Cursor select(){
SQLiteDatabase db = getReadableDatabase();
return db.query(
tbname,
new String[]{"_id","tname","tage","ttel","taddr"},
null,
null, null, null, "_id desc");
}
關於db.query方法的參數,有很多.
參數1:表名
參數2:返回數據包含的列信息,String數組里放的都是列名
參數3:相當於sql里的where,sql里where後寫的內容放到這就行了,例如:tage>?
參數4:如果你在參數3里寫了?(知道我為什麼寫tage>?了吧),那個這里就是代替?的值 接上例:new String[]{"30"}
參數5:分組,不解釋了,不想分組就傳null
參數6:having,想不起來的看看SQL
參數7:orderBy排序
SQLiteOpenHelper我們繼承使用的
SQLiteDatabase增刪查改都離不開它,即使你直接用sql語句,也要用到execSQL(sql)
二、這里無非是對DatabaseHelper類定義方法的調用.
Android查詢出來的結果一Cursor形式返回
cursor = sqLiteHelper.select();//是不是很簡單?
查詢出來的cursor一般會顯示在listView中,這就要用到剛才提到的SimpleCursorAdapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.list_row,cursor,new String[]{"tname","ttel"},new int[]{R.id.TextView01,R.id.TextView02});

⑺ 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

⑻ 如何連接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

<?php
echo"Welcome, I am connecting Android to PHP, MySQL";
?>4. 創建MySQL資料庫和表

在本教程中,我創建了一個簡單的只有一張表的資料庫。我會用這個表來執行一些示例操作。現在,請在瀏覽器中輸入http://localhost/phpmyadmin/,並打開phpmyadmin。你可以用PhpMyAdmin工具創建資料庫和表。

創建資料庫和表:資料庫名:androidhive,表:proct

CREATE DATABASE androidhive;
CREATE TABLE procts(
pid int(11) primary key auto_increment,
name varchar(100) not null,
price decimal(10,2) not null,
description text,
created_at timestamp defaultnow(),
updated_at timestamp
);5. 用PHP連接MySQL資料庫

現在,真正的伺服器端編程開始了。新建一個PHP類來連接MYSQL資料庫。這個類的主要功能是打開資料庫連接和在不需要時關閉資料庫連接。

新建兩個文件db_config.php,db_connect.php

db_config.php--------存儲資料庫連接變數
db_connect.php-------連接資料庫的類文件

db_config.php

<?php
/*
* All database connection variables
*/
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "androidhive"); // database name
define('DB_SERVER', "localhost"); // db serverdb_connect.php

<?php
/**
* A class file to connect to database
*/
classDB_CONNECT {
// constructor
function__construct() {
// connecting to database
$this->connect();
}
// destructor
function__destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
functionconnect() {
// import database connection variables
require_once__DIR__ . '/db_config.php';
// Connecting to mysql database
$con= mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) ordie(mysql_error());
// Selecing database
$db= mysql_select_db(DB_DATABASE) ordie(mysql_error()) ordie(mysql_error());
// returing connection cursor
return$con;
}
/**
* Function to close db connection
*/
functionclose() {
// closing db connection
mysql_close();
}
}
?>怎麼調用:當你想連接MySQl資料庫或者執行某些操作時,可以這樣使用db_connect.php

$db= newDB_CONNECT(); // creating class object(will open database connection)

⑼ 如何連接android和php mysql資料庫

使用JSON連接Android和PHP Mysql資料庫方法:
1、打開安裝WAMP Server的文件夾,打開www文件夾,為你的項目創建一個新的文件夾。必須把項目中所有的文件放到這個文件夾中。
2、新建一個名為android_connect的文件夾,並新建一個php文件,命名為test.php,嘗試輸入一些簡單的php代碼(如下所示)。
test.php
<?php
echo"Welcome, I am connecting Android to PHP, MySQL";
?>
3、創建MySQL資料庫和表
創建了一個簡單的只有一張表的資料庫。用這個表來執行一些示例操作。現在,請在瀏覽器中輸入http://localhost/phpmyadmin/,並打開phpmyadmin。你可以用PhpMyAdmin工具創建資料庫和表。
創建資料庫和表:資料庫名:androidhive,表:proct
CREATE TABLE procts(
pid int(11) primary key auto_increment,
name varchar(100) not null,
price decimal(10,2) not null,
description text,
created_at timestamp default now(),
updated_at timestamp
);
4、用PHP連接MySQL資料庫
現在,真正的伺服器端編程開始了。新建一個PHP類來連接MYSQL資料庫。這個類的主要功能是打開資料庫連接和在不需要時關閉資料庫連接。
新建兩個文件db_config.php,db_connect.php
db_config.php--------存儲資料庫連接變數
db_connect.php-------連接資料庫的類文件
db_config.php
<?php
/*
* All database connection variables
*/
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "androidhive"); // database name
define('DB_SERVER', "localhost"); // db server
?>
5、在PHP項目中新建一個php文件,命名為create_proct.php,並輸入以下代碼。該文件主要實現在procts表中插入一個新的產品。
<?php

/*
* Following code will create a new proct row
* All proct details are read from HTTP Post Request
*/

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {

$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// mysql inserting a new row
$result = mysql_query("INSERT INTO procts(name, price, description) VALUES('$name', '$price', '$description')");

// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Proct successfully created.";

// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";

// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}
?>
JSON的返回值會是:
當POST 參數丟失
[php] view plain
{
"success": 0,
"message": "Required field(s) is missing"
}

⑽ Android 怎麼連接遠程資料庫

想實現一個功能即讓android訪問遠程資料庫,但是網上很多人都不建議直連。據說問題多多。那麼中間就加個第三者吧。
實現思路:在資料庫和Android客戶端添加一個webservice,處理每次客戶端發來的請求。而在android客戶端使用ksoap2解析webservice返回的數據。
一 webservice 端,我使用序列化的方式實現的。不知道這里跟xml的實現哪個對手機來說更好。這里先放下,以後研究。
1.我使用的是xfire。新建一個webservice項目,然後我們開始寫代碼
2.一個介面
Java代碼
public interface ICompany {
public List<Company> getCompanyList();
}
3一個實現類
Java代碼
public class ICompanyImp implements ICompany {
CompanyDAO com=new CompanyDAO();
//得到所有公司列表
public List<Company> getCompanyList() {
List<Company> list=new ArrayList<Company>();
try {
list=com.getCompanyList();
} catch (SQLException e) {
e.printStackTrace();
list=null;
}
return list;
}
}
注意: 我這里的返回值是list,不少webservice的基本類型,所以需要為它配置文件 介面+.aegis.xml
4 介面+.aegis.xml
Xml代碼
<?xml version="1.0" encoding="UTF-8"?>
<mappings>
<mapping>
<!--
<method name="getCollectionsRowCount">
<parameter index="0" componentType="java.lang.String"/>
</method>
-->
<!-- 返回的類型是Map的話,做法和List一樣。但定義的類型,是Map中的Value部分 -->
<method name="getCompanyList">
<return-type componentType="bean.Company"/>
</method>
</mapping>
</mappings>

5.service.xml
Xml代碼
<?xml version="1.0" encoding="UTF-8"?>
<beans >
<service xmlns="http://xfire.codehaus.org/config/1.0"
xmlns:s="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<name>MyService</name>
<serviceClass>main.service.ICompany</serviceClass>
<implementationClass>main.service.ICompanyImp</implementationClass>

<style mce_bogus="1">wrapped</style>
<use>literal</use>
<scope>application</scope>
<namespace>http://android.googlepages.com/</namespace>
</service>
</beans>

發布項目後,運行效果如圖:

項目結構:

二 android客戶端

因為ksoap2解析webservice得到的數據類似於以下:getCompanyListResponse{out=anyType{Company=anyType{company=安徽江淮汽車股份有限公司; id=1; }; }; }
1 解析類:MyWebServiceHelper
Java代碼
public class MyWebServiceHelper {

// WSDL文檔中的命名空間
private static final String targetNameSpace = "http://android.googlepages.com/";

// WSDL文檔中的URL
private static final String WSDL = "http://192.168.1.144:8080/oilservice/services/MyService";
// 需要調用的方法名(獲得Myervices中的helloWorld方法)

//需要調用的方法名(獲得Myervices中的login方法)
private static final String getCompany="getCompanyList";

public List<Company> getCompanyList( ) {

List<Company> list=new ArrayList<Company>();

SoapObject request =new SoapObject(targetNameSpace,getCompany);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);

envelope.dotNet = false;
envelope.setOutputSoapObject(request);

AndroidHttpTransport httpTranstation = new AndroidHttpTransport (WSDL);

try {
httpTranstation.call(targetNameSpace+getCompany, envelope);
SoapObject soapObject = (SoapObject) envelope.getResponse();
//如果獲取的是個集合,就對它進行下面的操作
if(soapObject.getName()=="anyType") {
//遍歷Web Service獲得的集合
for(int i=0;i<soapObject.getPropertyCount();i++){
Company m=new Company();

//獲取單條的數據
SoapObject soapChilds =(SoapObject)soapObject.getProperty(i);

//對單個的數據進行再次遍歷,把它的每行數據讀取出來
m.setId(Integer.parseInt(soapChilds.getProperty("id").toString()));
m.setCompany(soapChilds.getProperty("company").toString());

/*
//獲取實體類的所有屬性
Field[] field = m.getClass().getDeclaredFields();

//遍歷所有屬性,第一個是序列化的id,serialVersionUID,用不到。
for(int j=0 ; j<field.length ; j++){
//獲取屬性的名字
String name = field[j].getName();
System.out.println(name);

}*/
// }

list.add(m);
}

}

} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}

return list;
}
}

2 實現類:

Java代碼
public class OilActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Spinner spinner = (Spinner) findViewById(R.id.company);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);

//調用自已寫的webService
MyWebServiceHelper webServiceHelper=new MyWebServiceHelper();
List<Company> compnayList= webServiceHelper.getCompanyList();

for(int i=0;i<compnayList.size();i++){
adapter.add(compnayList.get(i).getCompany());
}

spinner.setAdapter(adapter);

}
}
3 兩個項目中都用到的bean
Java代碼
public class Company implements Serializable{

private static final long serialVersionUID = 1L;

private int id;
private String company;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}

}

最後測試以下,list返回正確。效果圖:

3項目結構:

參考文章:
http://ksoap2.sourceforge.net/doc/api/ ksoap2的API
http://topic.csdn.net/u/20110412/16/0341626d-8576-4dda-b9e4-aab3ff50c980.html 關於list處理的帖子
http://blog.csdn.net/haha_mingg/article/details/6338332,總的思路的實現。在此感謝作者的無私奉獻
android 初學,願與大家相互交流。共同進步。