📄 records.java
字号:
//声明本类包含在包examples.jdbc.mssqlserver4中
package examples.jdbc.mssqlserver4;
//声明本类要引入的其他包和类
import java.sql.*;
import java.util.Properties;
/**
* 这个简单的实例演示JDBC如何用来执行DDL和DML。
*/
public class records {
public static void main(String argv[])
{
//声明连接,Statement,PreparedStatement和结果集变量
java.sql.Connection conn = null;
java.sql.Statement stmt = null;
java.sql.PreparedStatement pstmt = null;
java.sql.ResultSet rs = null;
try {
//声明属性变量
Properties props = new Properties();
//设置属性:用户,密码和服务器
props.put("user", "sa");
props.put("password", "secret");
props.put("server", "myHOST:1433");
//加载驱动程序
Driver myDriver = (Driver)
Class.forName("weblogic.jdbc.mssqlserver4.Driver").newInstance();
//建立连接
conn = myDriver.connect("jdbc:weblogic:mssqlserver4", props);
//创建SQL语句对象
stmt = conn.createStatement();
// 创建临时表
stmt.execute("create table #empdemo(empid int, name char(30), dept int)");
// 插入10个记录
System.out.println("Inserting 10 records...");
String inssql = "insert into #empdemo(empid, name, dept) values (?, ?, ?)";
//创建PreparedStatement对象
pstmt = conn.prepareStatement(inssql);
// 插入10个记录
for (int i = 0; i < 10; i++) {
pstmt.setInt(1, i);
pstmt.setString(2, "Person " + i);
pstmt.setInt(3, i);
pstmt.execute();
}
//关闭
pstmt.close();
// 更新10个记录
System.out.println("Updating 10 records...");
String updsql = "update #empdemo set dept = dept + ? where empid = ?";
pstmt = conn.prepareStatement(updsql);
// 更新10个记录
for (int i = 0; i < 100; i++) {
pstmt.setInt(1, i);
pstmt.setInt(2, i);
pstmt.execute();
}
// 获取当前内容并打印
rs = stmt.executeQuery("select * from #empdemo");
//打印结果集
while (rs.next())
{
System.out.println( rs.getInt(1) + ", "
+ rs.getString(2) + ", "
+ rs.getInt(3));
}
} catch (Exception e) {
//异常处理
System.out.println("Exception was thrown: " + e.getMessage());
} finally { //alwawy close connections in a finally block
//关闭
try {
if (stmt != null)
stmt.close();
if (pstmt != null)
pstmt.close();
if (conn != null)
conn.close();
} catch (SQLException sqle) {
//异常处理
System.out.println("SQLException was thrown: " + sqle.getMessage());
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -