Connecting to a SQL Server in Java
Basic Connection to a MS SQL Server in Java
Copy this code and paste it in your HTML
import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
import java.sql.*;
public void connectToDB() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.
out.
printf(" Unable to load JDBC driver... '%s'\n", e.
getMessage()); return;
}
if (true) {
try {
String connectionString
= "jdbc:sqlserver://OPENBOX\\WRR;databaseName=WRAP301"; System.
out.
println(" Connection string = " + connectionString
); con
= DriverManager.
getConnection(connectionString,
"WRAP301User",
"1"); System.
out.
printf(" Unable to connect to DB... '%s'\n", e.
getMessage()); }
}
public void useDB() {
try {
// perform query on database and retrieve results
String sql
= "SELECT * FROM TableName"; System.
out.
println(" Performing query, sql = " + sql
); System.
out.
println(" Displaying Query Result"); while (result.next()) {
String surname
= result.
getString("surname"); String name
= result.
getString("name"); String phone
= result.
getString("phone"); String cell
= result.
getString("cell"); System.
out.
println(" " + surname
+ ", " + name
+ ", (p) " + phone
+ ", (c) " + cell
); }
result.close();
System.
out.
println(" Was not able to query database..."); }
}
public void addRecord() {
try {
String sql
= "INSERT INTO Person VALUES ('Somesurnameelse', 'Aname', '1234', '5678')"; stmt.execute(sql);
System.
out.
println("\tDone!"); System.
out.
println("Could not insert new record... " + e.
getMessage()); }
}
public void getMetaData() {
try {
// perform query on database and retrieve results
String sql
= "SELECT * FROM TableName"; System.
out.
println(" Performing query, sql = " + sql
);
int columns = meta.getColumnCount();
System.
out.
println("\tColumns = " + columns
); for (int i = 1; i <= columns; i++) {
String colName
= meta.
getColumnLabel(i
); String colType
= meta.
getColumnTypeName(i
); System.
out.
println("\tcol[" + i
+ "]: name = " + colName
+ ", type = " + colType
); }
int row = 0;
while (result.next()) {
// get values from current tuple
row++;
String line
= "\tRow[" + row
+ "]="; for (int i = 1; i <= columns; i++) {
line = line.concat(result.getString(i) + " ");
}
}
System.
out.
println("Could not query database... " + e.
getMessage()); }
}
public void disconnectDB() {
try {
con.close();
System.
out.
println(" Unable to disconnect from database"); }
}
}
URL: basicdtabasesql
Report this snippet
Comments
Subscribe to comments