sqlJdbcUtil.jjava
Posted yachao1120
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sqlJdbcUtil.jjava相关的知识,希望对你有一定的参考价值。
package bookManage;
import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.mysql.jdbc.CallableStatement;
public class sqlJdbcUtil {
public static void main(String[] args) {
//Conn();
try {
testCallablestatement();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static SqlHelper sh;
private static java.sql.Statement statement;
public static void testCallablestatement() throws Exception{
Connection conn=null;
String sql="exec dbo.usp_getuserinfo ?";
java.sql.CallableStatement cstmt=null;
ResultSet rs=null;
try {
conn=sh.getConnect();
cstmt=conn.prepareCall(sql);
cstmt.setString(1, "zhangsan");
rs=cstmt.executeQuery();
while(rs.next()) {
String name=rs.getString("name");
String pwd=rs.getString("pwd");
System.out.println(name);System.out.println(pwd);
System.out.println("-------------------");
}
}catch(Exception ex) {
ex.printStackTrace();
}finally {
sh.releaseConn(cstmt, conn);
}
}
public static void testResultSet()throws Exception {
Connection conn=null;
PreparedStatement psmt=null;
ResultSet rs=null;
try {
conn=sh.getConnect();
statement=conn.createStatement();
String sname="zhangsan";String spwd="1234";
String sql_select="SELECT id,name,pwd FROM dbo.fm_userinfo where name= ‘"+sname+"‘ and pwd=‘"+spwd+"‘";
//执行查询 得到resultset
rs=statement.executeQuery(sql_select);
//处理ResultSet
while(rs.next()) {
int id=rs.getInt(1);
String name=rs.getString("name");
String pwd=rs.getString("pwd");
System.out.println(name);System.out.println(pwd);
System.out.println("-------------------");
}
//第二种取值的方式 预编译的处理方式
String sSql="SELECT id,name,pwd FROM dbo.fm_userinfo where name= ? and pwd= ?";
psmt=conn.prepareStatement(sSql);
psmt.setString(1, "zhangsan");
psmt.setString(2, "1234");
rs=psmt.executeQuery();
//处理ResultSet
while(rs.next()) {
String name=rs.getString("name");
String pwd=rs.getString("pwd");
System.out.println(name);System.out.println(pwd);
System.out.println("-------------------");
}
}catch(Exception ex) {
ex.printStackTrace();
}finally {
sh.releaseConn(psmt, conn);
}
}
//teststatement
public static void testStatement() throws Exception {
//获取数据库链接
Connection conn=null;
PreparedStatement psmt=null;
try {
conn=sh.getConnect();
String sql_update="UPDATE dbo.fm_userinfo SET pwd=‘1234‘ WHERE id=1";
String sql_insert="INSERT INTO dbo.fm_userinfo( name, pwd )VALUES(‘wangwu‘,‘wangwu‘)";
statement=conn.createStatement();
statement.executeUpdate(sql_update);
statement.execute(sql_insert);
System.out.println("更新操作成功执行!");
}catch(Exception ex) {
ex.printStackTrace();
}finally {
sh.releaseConn(psmt, conn);
}
}
}
以上是关于sqlJdbcUtil.jjava的主要内容,如果未能解决你的问题,请参考以下文章