import java.sql.*;
import java.util.*;
public class SQL
{
private Connection conn;
private String connStr, sqlStr;
private String useName, passWord;
private PreparedStatement ps;
private ResultSet rs;
// CallableStatement callProc
private StringBuffer strBuf = new StringBuffer();
public Connection getConnection()
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // 数据库驱动加载
} catch (ClassNotFoundException e)
{
System.out.println("数据库驱动加载失败!");
}
try
{
connStr = "jdbc:sqlserver://localhost:1433;DatabaseName=TMP"; // 定义连接数据库URL
useName = "sa";
passWord = "";
conn = DriverManager.getConnection(connStr, useName, passWord); // 连接数据库
if (conn != null)
System.out.println("数据库连接OK");
} catch (Exception e)
{
System.out.println("数据库连接失败");
}
return conn;
}
public void getData() // throws SQLException
{
strBuf.delete(0, strBuf.length());
sqlStr = "select * from TableA";
try
{
if (conn == null || conn.isClosed())
conn = getConnection();
} catch (SQLException e1)
{
e1.printStackTrace();
}
try
{
ps = conn.prepareStatement(sqlStr);
rs = ps.executeQuery();
while (rs.next())
{
// strBuf.append("1").append(rs.getString(1));
// strBuf.append("1:").append(rs.getString("A"));
strBuf.append(rs.getString("A")).append("--")
.append(rs.getString("B")).append("--")
.append(rs.getString("C")).append("--")
.append(rs.getString("D"));
strBuf.append("\r");
}
System.out.println(strBuf);
System.out.println("-----------------------");
} catch (SQLException e)
{
e.printStackTrace();
} finally
{
try
{
rs.close();
ps.close();
conn.close();
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
public void insertData() //插入数据,删除、更新同理
{
strBuf.delete(0, strBuf.length());
sqlStr = "insert into TableA(B, C, D) values(?, ?, ?)";
try
{
if (conn == null || conn.isClosed())
conn = getConnection();
} catch (SQLException e1)
{
e1.printStackTrace();
}
try
{
ps = conn.prepareStatement(sqlStr);
ps.setString(1, "B10");
ps.setDouble(2, 10);
ps.setString(3, "D10");
ps.executeUpdate();
System.out.println("-----------------------");
} catch (Exception e)
{
e.printStackTrace();
} finally
{
try
{
rs.close();
ps.close();
conn.close();
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
public void callProc() //调用存储过程,有返回值
{
strBuf.delete(0, strBuf.length());
sqlStr = "";
try
{
if (conn == null || conn.isClosed())
{
conn = getConnection();
}
} catch (SQLException e)
{
e.printStackTrace();
}
try
{
CallableStatement callProc = conn.prepareCall("{call sp_TableA(?, ?)}");
callProc.setInt(1, 4);
callProc.registerOutParameter(2, java.sql.Types.VARCHAR);
callProc.execute();
System.out.println(callProc.getString(2));
System.out.println("-----------------------");
} catch (SQLException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
SQL sqlDemo = new SQL();
// sqlDemo.getConnection();
sqlDemo.getData();
sqlDemo.insertData();
sqlDemo.callProc();
}
}