liangoogle

liangoogle
随笔 - 9, 文章 - 0, 评论 - 3, 引用 - 0
数据加载中……

java 连接数据库

public class JDBCTest {
public static void main(String[] arg) {
// 1. 注册驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}

// 声明变量,使用,而后关闭
Connection conn = null; // 数据库连接
Statement stmt = null; // 数据库表达式
ResultSet rs = null; // 结果集

try {
// 2. 获取数据库的连接
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/student", "root", "");

// 3. 获取表达式
stmt = conn.createStatement();
System.out.println("请输入操作指令:");
BufferedReader sReader = new BufferedReader(new InputStreamReader(
System.in));
String aaString = sReader.readLine();
String args[]=aaString.split(" ");
// stmt.execute(delsql);
if (args[0].equals("add")) {
// str=new String(rs.getBytes(1),"UTF-8")
// args[2] = new String(args[2]);
String addString="insert into stuinfo (stuno,stuname) values ('"+args[1]+"','"+args[2]+"')";
stmt.execute(addString);
}else if (args[0].equals("del")) {
String delsql = "delete from stuinfo where stuno="+args[1];
stmt.execute(delsql);
}
else  if (args[0].equals("update")) {
String update="update stuinfo set stuname='"+args[2]+"' where stuno='"+args[1]+"'";
stmt.executeUpdate(update);
}

else if (args[0].equals("select")) {

// String sql = "select * from stuinfo ";
// String selString="SELECT * FROM `stuinfo` WHERE stuname="+arg[2];
String selString2="select * from stuinfo where stuno='"+args[1]+"'";
// rs = stmt.executeQuery(selString);
rs=stmt.executeQuery(selString2);
}
// 4. 执行SQL

System.out.println("-----------------");
System.out.println("执行结果如下所示:");
System.out.println("-----------------");
System.out.println(" 学号" + "\t" + " 姓名");
System.out.println("-----------------");
// 5. 现实结果集里面的数据
String name = null;
while (rs.next()) {
name = rs.getString("stuname");
// name = new String(name.getBytes("ISO-8859-1"), "GB2312");
System.out.println("" + rs.getString("stuno") + "\t" + name);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}

}
}

posted on 2011-04-28 19:33 haojinlian 阅读(233) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: