📄 sample.java
字号:
import java.sql.*;
import java.net.URL;
class sample{
public static void main (String args[]) {
String url = "jdbc:microsoft:sqlserver://localhost:1433;User=JavaDB;Password=javadb;DatabaseName=northwind";
String query = "Select * From FirstTable";
String query1 = "Select Distinct Types From FirstTable";
String query2 = "Select ID,Name From FirstTable Where ID<10";
try {
// Load the SQL Server JDBC driver
Class.forName ("com.microsoft.jdbc.sqlserver.SQLServerDriver");
Connection con = DriverManager.getConnection (
url);
// Create a Statement object so we can submit
// SQL statements to the driver
Statement stmt = con.createStatement ();
// Submit a Insert,there two different insert operation
ResultSet rs = stmt.executeQuery(query);
//dispResultSet (rs);
//rs = stmt.executeQuery(query2);
//dispResultSet (rs);
//rs = stmt.executeQuery(query);
// Display all columns and rows from the result set
dispResultSet (rs);
// Close the result set
rs.close();
// Close the statement
stmt.close();
// Close the connection
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) {
// Got some other type of exception. Dump it.
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 + -