⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 prepared.java

📁 本套光盘提供了本书各章实例的所需的部分源程序文件以及数据库文件。读者 需要使用JDK 1.4(必需)版
💻 JAVA
字号:
import java.sql.*;
import java.net.URL;

class prepared 
{
	public static void main (String args[]) 
	{
		String url ="jdbc:microsoft:sqlserver://localhost:1433;User=JavaDB;Password=javadb;DatabaseName=northwind";
		String query = "Select * From FirstTable";

		try 
		{

			//加载SQL Server JDBC驱动程序driver
			Class.forName ("com.microsoft.jdbc.sqlserver.SQLServerDriver");
			Connection con = DriverManager.getConnection (url);

			//建立一个PreparedStatement对象,用这个对象向驱动程序发送SQL语句
		
			PreparedStatement pstmt = con.prepareStatement("UPDATE FirstTable SET Name =? WHERE ID =?");

			//运行PreparedStatement对象语句
			for(int i = 1;i<8;i++)
			{
				//setvalue1----Name
				pstmt.setString(1,"test"+i);
				//setvalue2----ID 
				pstmt.setInt(2,i);

				// 提交更新
 
				pstmt.executeUpdate();
			}
			pstmt.close();		

			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery(query);
		
			// 显示结果集的所有行和列
			dispResultSet (rs);

			// 关闭结果集
			rs.close();

			// 关闭statement对象
			stmt.close();

			// 关闭连接
			con.close();
		}
		catch (SQLException ex) 
		{

			System.out.println ("\n*** SQLException caught ***\n");

			while (ex != null) 
			{
				System.out.println ("SQLState: " +	ex.getSQLState ());
				System.out.println ("Message:  " + ex.getMessage ());
				System.out.println ("Vendor:   " +	ex.getErrorCode ());
				ex = ex.getNextException ();
				System.out.println ("");
			}
		}
		catch (java.lang.Exception ex) 
		{

			//捕获其他类型的例外
			ex.printStackTrace ();
		}
	}

//-------------------------------------------------------------------
// dispResultSet
// 现实整个结果届中的所有的行和列
//-------------------------------------------------------------------

private static void dispResultSet (ResultSet rs)
	throws SQLException
{
	int i;

	// Get the ResultSetMetaData.  This will be used for
	// the column headings

	ResultSetMetaData rsmd = rs.getMetaData ();

	// Get the number of columns in the result set

	int numCols = rsmd.getColumnCount ();

	// Display column headings

	for (i=1; i<=numCols; i++) {
		if (i > 1) System.out.print(",     ");
		System.out.print(rsmd.getColumnLabel(i));
	}
	System.out.println("");
	System.out.println("");
	
	// Display data, fetching until end of the result set

	boolean more = rs.next ();
	while (more) {

		// Loop through each column, getting the
		// column data and displaying

		for (i=1; i<=numCols; i++) {
			if (i > 1) System.out.print(",  ");
			System.out.print(rs.getString(i));
		}
		System.out.println("");

		// Fetch the next result set row

		more = rs.next ();
	}
}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -