.:: CODE SNIPPET ::.

"Your time is limited, so don't waste it living someone else's life"

Connect to sqlsever express by java


Here are a helping code to connect to SQLServer Express Edition by Java. The code reads the information from a file named “SysConfig.cfg”

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.*;

/**
*
*/
public class DataConnection
{

private static Connection conn = null;

public static Connection getConnection()
{
return conn;
}

Xem tiếp nhé

public DBHelper()
{
if (conn == null)
{
try
{
String url = DBHelper.getConnectionString();
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url);
}
catch (ClassNotFoundException e)
{
System.out.println(e);
}
catch (SQLException sql)
{
System.out.println(sql);
}
}
}

public static String getConnectionString()
{
Properties p = new Properties();
try
{
FileInputStream file = new FileInputStream("SysConfig.cfg");
p.load(file);
}
catch (Exception e)
{
javax.swing.JOptionPane.showMessageDialog(null, e.toString());
return "";
}
String server = p.getProperty("ServerName");
String instance = p.getProperty("Instance");
String port = p.getProperty("Port");
String databaseName = p.getProperty("Database");
String username = p.getProperty("User");
String password = p.getProperty("Password");
return "jdbc:sqlserver://" + server + ":" + port+ ";databaseName=" + databaseName  + ";User=" + username + ";Password=" + word;
}

}

(prmhuitedu)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: