//数据库信息
package com.android.cn;
public interface IDBDriver {
String DBDriver="com.mysql.jdbc.Driver";
String DBPATH="jdbc:mysql://127.0.0.1:3306/mydatabase";
String DBUSER="root";
String DBPW=null;
}
//操作数据库
package com.android.cn;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class COperation {
Connection connection = null;
Statement statement=null;
public COperation(){
Init();
}
public void Init(){
loadDB();
connectDatabase();
}
public void loadDB(){
try {
Class.forName(IDBDriver.DBDriver);
System.out.println("加载成功!");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void connectDatabase(){
try {
connection=DriverManager.getConnection(IDBDriver.DBPATH, IDBDriver.DBUSER, IDBDriver.DBPW);
statement=connection.createStatement();
System.out.println("连接成功!");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void insert(String tableName,String field,String value){
try {
if(statement!=null){
statement.execute("insert into "+tableName+" ("+field+") values('"+value+"');");
System.out.println("插入成功!");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void delete(String tableName,String id,int i){
try {
if(statement!=null){
statement.execute("delete from "+tableName+" where "+id+"="+i+";");
System.out.println("删除成功!");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void update(String tableName,String name,int id){
if(statement!=null){
try {
statement.execute("update "+tableName+" set name='"+name+"' where id="+id+"");
System.out.println("更新成功!");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void select(String tableName,int id){
if(statement!=null){
try {
ResultSet rs=statement.executeQuery("select * from "+tableName+" where id="+id+"");
if(rs!=null){
while(rs.next()){
System.out.println("name为:"+rs.getString("name")+" +
sex为:"+rs.getString("sex"));
}
}
else{
System.out.println("无数据!");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}