package com.lsq;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBC_1 {
/**尝试用JDBC的方式连接数据库
* 方法:加载JDBC驱动,连接数据库
* @author oxandboy
* @date 2014.4.22
*/
public static void main(String[] args)throws Exception{
JDBC_test JB=new JDBC_test();
//
String sql1="insert into users(counter,email,password) values('lsqdd','lsquan',1234)";
String sql2="delete from users where counter=\"lsqdd\"";
String sql3="select * from users";
String sql4="update users set email='liushuangquan',password=11111 where counter='lsq'";
JB.sql_Update(sql4);
JB.sql_Query(sql3);
}
}
class JDBC_test{
//使用DriverManager类加载驱动
public static Connection con = null;//定义个mysql对象
public static Statement st=null;
//连接数据库
JDBC_test(){
try{
Class.forName("com.mysql.jdbc.Driver");//mysql驱动安装
con = DriverManager.getConnection("jdbc:mysql://localhost/my_zone","root","123456");//建立链接
if(con!=null)
System.out.println("数据库连接OK!");
st=con.createStatement();
}catch(Exception e){
System.out.println("靠,出错了!"+e.getMessage());
}
}
//执行数据库
public void sql_Query(String sql){
try {
//获得结果集
ResultSet result=st.executeQuery(sql);
ResultSetMetaData rsmd=result.getMetaData();
while(result.next()){
System.out.println("id "+result.getString("id")+" | 学号 "+result.getString("counter")+" |姓名 "+result.getString("email")+" "+result.getRow());
}
System.out.println("ok");
} catch (SQLException e) {
e.printStackTrace();
}
}
//插入|删除|更改|
public void sql_Update(String sql){
try {
st.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}