1 PackageOrg.warnier.zhang.jdbc;2 3 Importjava.sql.Connection;4 ImportJava.sql.DriverManager;5 ImportJava.sql.ResultSet;6 ImportJava.sql.ResultSetMetaData;7 Importjava.sql.SQLException;8 Importjava.sql.Statement;9 Ten Public classSqlservertest { One A /** - * @paramargs - * @throwsclassnotfoundexception the * @throwsSQLException - */ - Public Static voidMain (string[] args)throwsClassNotFoundException, - SQLException { + //load the driver; (The virtual machine loads the class, not the one that is used during programming.) ) -Class.forName ("Com.microsoft.sqlserver.jdbc.SQLServerDriver"); + A //establish database connection; atConnection Connection = drivermanager.getconnection ("JDBC:SQLSERVER://LOCALHOST:1433;DATABASENAME=TEST;USER=SA; Password=*ying1993ad "); - - //create the SQL statement, execute the statement, return the result set; -Statement Statement =connection.createstatement (); -ResultSet ResultSet = Statement.executequery ("SELECT * from [user];"); - //Note: The SELECT * from user error causes: in //Error statement: There is a syntax error near the keyword ' user '; - //user is the keyword in the SQL statement, if you want to use user as the table name, you must enclose the user in square brackets [], that is [user]; to + //processing result sets (including metadata); - //Print property name; theResultSetMetaData Rsmetadata =Resultset.getmetadata (); * for(inti = 1; I <= rsmetadata.getcolumncount (); i++) { $System.out.printf ("%-8s\t", Rsmetadata.getcolumnname (i));Panax Notoginseng } - System.out.println (); the + //print attribute values; A while(Resultset.next ()) { the for(inti = 1; I <= rsmetadata.getcolumncount (); i++) { +System.out.printf ("%-12s\t", resultset.getstring (i)); - } $ System.out.println (); $ } - - //close the database connection; (Connecting the database is a big overhead in Java applications.) ) the connection.close (); - }Wuyi the}
JDBC Programming: Connecting SQL Server Detailed example