1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class SQLServerQuery {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionString = "jdbc:sqlserver://localhost:3888;database=AdventureWorks;user=sa;password=demo";
conn = DriverManager.getConnection(connectionString);
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT FirstName, LastName FROM Person.Contact");
while (rs.next()) {
String contact = rs.getString("FirstName")
+ " " + rs.getString("LastName");
System.out.println(contact);
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
}
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
}
}
}
}
} |
Partager