Java学习笔记――JDBC之与数据库MySQL的连接以及增删改查等操作 (二)

2014-11-24 10:11:48 · 作者: · 浏览: 1
ll;
}
if (connection != null) {
connection.close();
connection = null;
}
} catch (SQLException e2) {
// TODO: handle exception
}
}
return count;
}
应用:
[java]
System.out.println(jDao.Update("INSERT INTO t_user(username,password,sex) values('hehe','131','n');"));

System.out.println(jDao.Update("INSERT INTO t_user(username,password,sex) values('hehe','131','n');"));输出值为 1 则证明添加成功。


查询类 SQL 并返回多条记录
[java]
//执行一条查询类SQL,返回多条记录集
public void Qurty(String sql) {
getConnection();
try {
statement = connection.createStatement();
rSet = statement.executeQuery(sql);
System.out.println("id\t" + "realName\t"+"school\t");
while (rSet.next()) {
System.out.println(rSet.getRow()+ "----" + rSet.getString("id") + "\t" + rSet.getString("realName") + "\t" + rSet.getString("school") + "\t");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
if (statement != null) {
statement.close();
statement = null;
}
if (rSet != null) {
rSet.close();
rSet = null;
}
} catch (SQLException e2) {
// TODO: handle exception
}
}
}

//执行一条查询类SQL,返回多条记录集
public void Qurty(String sql) {
getConnection();
try {
statement = connection.createStatement();
rSet = statement.executeQuery(sql);
System.out.println("id\t" + "realName\t"+"school\t");
while (rSet.next()) {
System.out.println(rSet.getRow()+ "----" + rSet.getString("id") + "\t" + rSet.getString("realName") + "\t" + rSet.getString("school") + "\t");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
if (statement != null) {
statement.close();
statement = null;
}
if (rSet != null) {
rSet.close();
rSet = null;
}
} catch (SQLException e2) {
// TODO: handle exception
}
}
}应用举例:
[java]
jDao.Qurty("SELECT * FROM t_user WHERE sex='女';");
System.out.println("-----------------------------");
jDao.Qurty("SELECT * FROM t_user;");
System.out.println("-----------------------------");

jDao.Qurty("SELECT * FROM t_user WHERE sex='女';");
System.out.println("-----------------------------");
jDao.Qurty("SELECT * FROM t_user;");
System.out.println("-----------------------------");

查询类 SQL 并返回一条记录
[java]
//执行一条查询类SQL,返回单条记录集
public void QurtyByUnique(String sql) {
getConnection();
try {
statement = connection.createStatement();
rSet = statement.executeQuery(sql);
System.out.println("id\t" + "realName\t"+"school\t");
if (rSet.next()) {
System.out.println(rSet.getInt("id") + "\t" + rSet.getString("realName") + "\t" + rSet.getString("school") + "\t");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
if (statement != null) {
statement.close();
statement = null;
}
if (rSet != null) {
rSet.close();
rSet = null;
}
} catch (SQLExcep