我就是憨批,真的是佛了,让我乱删还得重新连又多搞了一个多小时,草
package com.example.listview;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
- Created by Administrator on 2017/12/14.
*/
public class DbUtil {
//连接数据库
private static Connection getSQLConnection(String ip,String user,String pwd,String db)
{
Connection con =null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
//一定要在AndroidManifest.xml中加入socket权限,不然会包权限错误
/*
*/
con = DriverManager.getConnection("jdbc:jtds:sqlserver://"+ip+":1433/"+db+";charset=utf-8",user,pwd);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
//登陆
public static String QuerySQL(){
String result="";
try {
//要想连接数据库必须导入相应的包在libs中(jtds-1.2.7.jar和sqljdbc.jar)
Connection conn = getSQLConnection("127.0.0.1","sa","huang0529","pro");
String sql = "SELECT * FROM student"; //查询语句
Statement stmt = conn.createStatement();//得到PreparedStatement对象
ResultSet rs = stmt.executeQuery(sql);//执行查询语句
while(rs.next())
{
String s1 = rs.getString("name");
String s2 = rs.getString("score");//列名
result += s1+" - " + s2 + "\n";
System.out.println(s1+" - "+s2);
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
result += "查询数据异常!"+e.getMessage();
}
return result;
}
public static void main(String[] args){
QuerySQL();
}
}这是as
package shu;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Testdb {
public static void main(String[] args) {
String JDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";// SQL数据库引擎
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=pro";// 数据源注意IP地址和端口号,数据库名字!!!
try {
Class.forName(JDriver);// 加载数据库引擎,返回给定字符串名的类
} catch (ClassNotFoundException e) {
// e.printStackTrace();
System.out.println("加载数据库引擎失败");
System.exit(0);
}
System.out.println("数据库驱动成功");
try {
String user = "root";// 你自己创建的用户名字和密码!!!!!!!!!!!!
String password ="root";
Connection con = DriverManager.getConnection(connectDB, user,
password);// 连接数据库对象
System.out.println("连接数据库成功");
Statement stmt = con.createStatement();// 创建SQL命令对象
// 创建表
System.out.println("查询");
System.out.println("开始读取数据");
ResultSet rs = stmt.executeQuery("SELECT * FROM student");// 返回SQL语句查询结果集(集合)
// 循环输出每一条记录
while (rs.next()) {
// 输出每个字段
System.out.println(rs.getString("id") + "\t"
+ rs.getString("name"));
}
System.out.println("读取完毕");
// 关闭连接
stmt.close();// 关闭命令对象连接
con.close();// 关闭数据库连接
} catch (SQLException e) {
e.printStackTrace();
// System.out.println("数据库连接错误");
System.exit(0);
}
}
}这是ecplise