android 连接数据库

不建议直连数据库,因为会把IP、用户名、密码暴露在apk中。Android连接数据库 就是 java连接数据库

1、jdbc包
2008 ,2005
如果不合适会报错:com.microsoft.sqlserver.jdbc.SQLServerException: 驱动程序无法使用安全套接字层(SSL)加密与 SQL Server 建立安全连接。

2、添加联网权限

3、注释掉
否则 Could not find class 'javax.sql.XAConnection', referenced from method com.microsoft.sqlserver.jdbc.SQLServerConnection.close

4、代码
package my.org.mysql;

import java.sql.*;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Android_sqlActivity extends Activity {
    /** Called when the activity is first created. */
	public static final String DBDriver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
	public static final String DBURL="jdbc:sqlserver://10.19.1.50:1433;DatabaseName=GuBei_Data";
	public static final String user="sa"; 
	public static final String password="123"; 
	 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        TextView myTxt=(TextView)findViewById(R.id.myTxt);
		try {
			Class.forName(DBDriver);
			Connection con=DriverManager.getConnection(DBURL,user,password);
			if(con!=null){
				Statement state=con.createStatement();
				   
				//数据库更新操作
				//state.executeUpdate("INSERT INTO tblComment(ID,Number,visitor,comments) VALUES(6,'view4','youke5','very well')");
				//state.executeUpdate("delete from tblComment where ID=6");
				   
				//数据库查询操作
				ResultSet res=state.executeQuery("select * from tblComment");
				String str="";
				while(res.next()){
					int id=res.getInt("ID");
					String name=res.getString("comments");
					str+=id+" "+name+"\r\n";
				}
				myTxt.setText(str);
				
				res.close();
				state.close();
				con.close();
			}
		} catch (Exception e) {
			myTxt.setText("error:  "+e);
			System.out.println("error:  "+e);
		}
        
    }
}



你可能感兴趣的:(SQL,Server,sql,server,android)