安卓app 怎么连接mysql

安卓app 怎么连接mysql,第1张

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 produced by a broken compiler.)

手机是不能直接去连接你服务器的mysql数据库

请在你的服务端写代码去连接mysql数据吧

Mysql连接方法

1. 加载数据库驱动: Class.forName("org.gjt.mm.mysql.Driver") //加载数据库驱动

String url = "jdbc:mysql://localhost:3306/test"

String user = "root"

String passowrd = "123456"

2. 获取数据库连接Connection con数= DriverManager.getConnection(url,user,password)

3. 获取SQL执行器 PreparedStatement prepare = con.prepareStatement("SQL语句")

4. 执行SQL语句,得到结果集 ResultSet result = prepare.executeQuery()

while(result.next()){

  //读取结果

}

最后不要忘记导入jdbc驱动包

纯工手打字,请采纳哈


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

原文地址: https://outofmemory.cn/zaji/6097081.html

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

发表评论

登录后才能评论

评论列表(0条)

保存