java实现mysql操作类分享 java连接mysql
相关软件和驱动:
mysql下载版本:4.1.11
http://dev.mysql.com/downloads/mysql/4.1.html
jdbc驱动下载版本:3.1.8
http://dev.mysql.com/downloads/connector/j/3.1.html
代码
code highlighting produced by actipro codehighlighter (freeware)http://www.codehighlighter.com/-->import java.sql.*;
public class mysql {
public static string url = "jdbc:mysql://localhost:3306/test";//characterencoding=gbk
public static string username = "root";
public static string password = "root";
public static connection con;
public static statement stmt;
public static resultset rs;
public static void main(string[] args) throws sqlexception {
connect();
operation();
stmt.close();
con.close();
}
public static void test() {
string sql_select = "select * from tablename where id=1";
string sql_insert = "insert into tablename (col1,col2..) values('1','2'...)";
string sql_update = "update tablename set colname='update' where id=1";
//insert(sql_insert);
//select(sql_select);
//update(sql_update);
}
public static void connect() {
// 定位驱动
try {
class.forname("com.mysql.jdbc.driver");
system.out.println("加载驱动成功!");
} catch (classnotfoundexception e) {
system.out.println("加载驱动失败!");
e.printstacktrace();
}
// 建立连接
try {
con = drivermanager.getconnection(url, username, password);
stmt = con.createstatement();
system.out.println("数据库连接成功!");
} catch(sqlexception e) {
system.out.println("数据库连接失败!");
}
}
public static void select(string sql) {
try {
rs = stmt.executequery(sql);
resultsetmetadata meta_data = rs.getmetadata();//列名
for (int i_col = 1; i_col <= meta_data.getcolumncount(); i_col++) {
system.out.print(meta_data.getcolumnlabel(i_col) + " ");
}
system.out.println();
while (rs.next()) {
for (int i_col = 1; i_col <= meta_data.getcolumncount(); i_col++) {
system.out.print(rs.getstring(i_col) + " ");
}
system.out.println();
}
rs.close();
}catch (exception e) {
system.out.println("数据查询失败!");
}
}
public static void insert(string sql) {
try {
stmt.clearbatch();
stmt.addbatch(sql);
stmt.executebatch();
system.out.println("数据插入成功!");
}catch (exception e) {
system.out.println("数据插入失败!");
}
}
public static void update(string sql) {
try {
stmt.executeupdate(sql);
system.out.println("数据更新成功!");
}catch (exception e) {
system.out.println("数据更新失败!");
}
}
}