I have MSSQL 2008 installed on my local PC, and my Java application needs to connect to a MSSQL database. I am a new to MSSQL and I would like get some help on creating user login for my Java application and getting connection via JDBC. So far I tried to create a user login for my app and used following connection string, but I doesn't work at all. Any help and hint will be appreciated.
jdbc:jtds:sqlserver://127.0.0.1:1433/dotcms
username="shuxer" password="itarator"
There are mainly two ways to use JDBC - using Windows authentication and SQL authentication. SQL authentication is probably the easiest. What you can do is something like:
String userName = "username";
String password = "password";
String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url, userName, password);
after adding sqljdbc4.jar to the build path.
For Window authentication you can do something like:
String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url);
and then add the path to sqljdbc_auth.dll as a VM argument (still need sqljdbc4.jar in the build path).
Please take a look here for a short step-by-step guide showing how to connect to SQL Server from Java using jTDS and JDBC should you need more details. Hope it helps!
You can use this :
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ConnectMSSQLServer
{
public void dbConnect(String db_connect_string,
String db_userid,
String db_password)
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,
db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String queryString = "select * from sysobjects where type='u'";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
ConnectMSSQLServer connServer = new ConnectMSSQLServer();
connServer.dbConnect("jdbc:sqlserver://<hostname>", "<user>",
"<password>");
}
}
I am also using mssql server 2008 and jtds.In my case I am using the following connect string and it works.
Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
Connection con = DriverManager.getConnection( "jdbc:jtds:sqlserver://<your server ip
address>:1433/zacmpf", userName, password );
Statement stmt = con.createStatement();
If your having trouble connecting, most likely the problem is that you haven't yet enabled the TCP/IP listener on port 1433. A quick "netstat -an" command will tell you if its listening. By default, SQL server doesn't enable this after installation.
Also, you need to set a password on the "sa" account and also ENABLE the "sa" account (if you plan to use that account to connect with).
Obviously, this also means you need to enable "mixed mode authentication" on your MSSQL node.
Try to use like this: jdbc:jtds:sqlserver://127.0.0.1/dotcms; instance=instanceName
I don't know which version of mssql you are using, if it is express edition, default instance is sqlexpress
Do not forget check if SQL Server Browser service is running.
You can try configure SQL server:
Step 1: Open SQL server 20xx Configuration Manager
Step 2: Click Protocols for SQL.. in SQL server configuration. Then, right click TCP/IP, choose Properties
Step 3: Click tab IP Address, Edit All TCP. Port is 1433
NOTE: ALL TCP port is 1433
Finally, restart the server.
Simple Java Program which connects to the SQL Server.
NOTE: You need to add sqljdbc.jar into the build path
// localhost : local computer acts as a server
// 1433 : SQL default port number
// username : sa
// password: use password, which is used at the time of installing SQL server management studio, In my case, it is 'root'
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Conn {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
Connection conn=null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=company", "sa", "root");
if(conn!=null)
System.out.println("Database Successfully connected");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Try this.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class SQLUtil {
public void dbConnect(String db_connect_string,String db_userid,
String db_password) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,
db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String queryString = "select * from cpl";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
} }
public static void main(String[] args) {
SQLUtil connServer = new SQLUtil();
connServer.dbConnect("jdbc:sqlserver://192.168.10.97:1433;databaseName=myDB",
"sa",
"0123");
}
}
Try this
Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
String url ="Jdbc:jtds:sqlsever://ip/instanceName;instance=instanceName;databseName=dbName;user=yourUser;password=yourpass;";
Related
We have a Utility Class that opens and disconnects the Derby DB Connection
The database is stored in a folder on C drive of a Windows 7 computer
The application is being written with JavaFX 8
We are NOT using transactions
Before using the Utility Class we would Open and Disconnect the connection with each CRUD function rs.close() con.close()
Our question has two parts
1. Do we really need to open and close the connection with each CRUD function?
2. Why is the Utility Class not closing the rs and stmnt?
The conn.close() fires when
We will post the code for the Utility Class and the Delete function
We are also using the code below in the Main Class to shutdown the Derby DB when the application is closed
private void handle(WindowEvent e) throws SQLException {
//Proper CLOSE of connection to DB keeps proper incrementing by 1 as set when the table is created
JDBCUtil.closeConnection(conn);
String conURL = "jdbc:derby:;shutdown=true";
try{
DriverManager.getConnection(conURL);
}catch (SQLException se){
if(!(se.getErrorCode() == 50000) && (se.getSQLState().equals("XJ015")))
System.err.println(se);
}
System.exit(0);
Platform.exit();
}
Utility Class
public class JDBCUtil {
public static Connection conn;
public static Connection getConnection() throws SQLException {
// The URL is specific to the JDBC driver and the database you want to connect
String dbName="InfoDB";
String dbURL = "jdbc:derby:C:/A_DerbyDataBase/DBName/" + dbName + ";create=true";
//String dbURL = "jdbc:derby:DATABASE_NAME;create=true";
// Set the user id and password
//String userId = "app";
//String password = "app";
// Get a connection
conn = DriverManager.getConnection(dbURL);
// Set the auto-commit to false ONLY if you use Transactions
/*conn.setAutoCommit(true);*/
System.out.println("111111111111111111111111111 Get Connection ");
return conn;
}
public static void closeConnection(Connection conn) throws SQLException {
if (conn != null) {
System.out.println("222222222222222222222 conn.close ");
conn.close();
}
}
public static void closeStatement(Statement stmnt) throws SQLException{
if (stmnt != null) {
System.out.println("3333333333333333333333 stmnt.close ");
stmnt.close();
}
}
public static void closeResultSet(ResultSet rs) throws SQLException {
if (rs != null) {
System.out.println("44444444444444444444444 rs.close ");
rs.close();
}
}
/*public static void commit(Connection conn) throws SQLException {
if (conn != null) {
conn.commit();
}
}
public static void rollback(Connection conn) throws SQLException {
if (conn != null) {
conn.rollback();
}
}*/
public static void main(String[] args) throws SQLException {
//conn = JDBCUtil.getConnection();
JDBCUtil.closeConnection(conn);
}
And the Delete Function
#FXML
private void onDelete(ActionEvent e) throws SQLException, IOException{
conn = JDBCUtil.getConnection();
String sql = "DELETE FROM infodata WHERE ID = ?";
pstmt = conn.prepareStatement(sql);
int ID = Integer.valueOf(txfID.getText());
pstmt.setInt(1, ID);
pstmt.executeUpdate();
pstmt.close();
JDBCUtil.closeConnection(conn);
ReadFromDB();
btnEdit.setVisible(false);
btnDelete.setVisible(false);
btnCancel.setVisible(false);
btnAdd.setVisible(true);
txfInfo.setText("Record Deleted");
}
Database Access with a Connection Pool
Rather than writing your own connection logic, I advise using a connection pool, for example see the Baeldung Hikari Tutorial. You can use it like this:
Initialize the connection pool in your application's init method.
When you want to use a connection, use the Java try-with-resources construct, which will auto-close the connection (returning it to the connection pool) when you are done with it.
In your application's stop method, close the connection pool.
Sample wrapper class for DataSource connections (copied from Baeldung Hikari link above):
public class DataSource {
private static HikariConfig config = new HikariConfig();
private static HikariDataSource ds;
static {
config.setJdbcUrl( "jdbc_url" );
config.setUsername( "database_username" );
config.setPassword( "database_password" );
config.addDataSourceProperty( "cachePrepStmts" , "true" );
config.addDataSourceProperty( "prepStmtCacheSize" , "250" );
config.addDataSourceProperty( "prepStmtCacheSqlLimit" , "2048" );
ds = new HikariDataSource( config );
}
private DataSource() {}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}
Sample database call using the Hikari connection pool with autoclose of connections using Java's try with resources construct (copied from Baeldung Hikari link above):
public static List<Employee> fetchData() throws SQLException {
String SQL_QUERY = "select * from emp";
List<Employee> employees = null;
try (Connection con = DataSource.getConnection();
PreparedStatement pst = con.prepareStatement( SQL_QUERY );
ResultSet rs = pst.executeQuery();) {
employees = new ArrayList<>();
Employee employee;
while ( rs.next() ) {
employee = new Employee();
employee.setEmpNo( rs.getInt( "empno" ) );
employee.setEname( rs.getString( "ename" ) );
employee.setJob( rs.getString( "job" ) );
employee.setMgr( rs.getInt( "mgr" ) );
employee.setHiredate( rs.getDate( "hiredate" ) );
employee.setSal( rs.getInt( "sal" ) );
employee.setComm( rs.getInt( "comm" ) );
employee.setDeptno( rs.getInt( "deptno" ) );
employees.add( employee );
}
}
return employees;
}
For more info read the Baeldung tutorial and the Hikari site documentation:
Link to HikariCP project.
Database Access without a Connection Pool
Now, you don't need to use a connection pool to do this, you can open and close a connection for each database call, however I would recommend using a connection pool for performance reasons and so that you don't end up trying to re-invent the wheel and ending up with something square rather than round.
I didn't try debugging or examining the connection utility class you have in your question, but, if you are going to replace it with a connection pool anyway, there is no reason to do that.
Sample code for accessing a database from JavaFX without a connection pool:
JavaFX MySQL connection example please
Non-Task based database access.
JavaFX - Background Thread for SQL Query which uses a Task based sample for db access.
Some of the sample code is written to be minimal to demonstrate particular purposes, such as access to a database and feedback of data from a given table to a UI, and not as a general purpose database utility. For a robust implementation for an application that uses many database queries, a connection pool or a dedicated database connection manager class (such as you have in your question), is preferred.
I've Encrypted connectionString section in web.config using ASPNET_REGIIS successfully.
however i've done this on my local machine.
When I tried to publish website on a shared hosting server I received a configuration file error.
Is there any way I could Encrypt on a shared hosting server using ASPNET_REGIIS without access to the physical server machine?
Thanks.
I found a solution, Might not be the best but I feel okay with it..
I encrypted web.Config once, using the first function.
I decrypt it on each call.
public static void EncryptConnString()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
ConfigurationSection section = config.GetSection("connectionStrings");
if (!section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
config.Save();
}
}
public static MySqlConnection DecryptConnString()
{
MySqlConnection conn = new MySqlConnection();
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
ConfigurationSection section = config.GetSection("connectionStrings");
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["DatabaseName"].ConnectionString);
return conn;
}
else
return null;
}
(using MySql)
I am new to the oracle database.
I installed OracleXE 11g on my machine. I created a separate test database[SID:testDB] from oracle default database(XE) referring this video. i created below things:
created windows service- OracleServicetestDB using below cmd:
oradim -new -sid testDB -startmode auto -pfile initTestDB.ora
created database
executed sql scripts
SQL> #?\rdbms\admin\catalog.sql
SQL> #?\rdbms\admin\catproc.sql
created user
After creating user/schema for this new database i am able to make connect it from sql developer and java/jdbc programme from other machine on the network.
I am surprised that i have not created any TNS listener or TNS entry for this database in tnsnames.ora but still i am able to connect with this database locally and remotely.
i am expecting answers of below questions:
how my testDB is connected without tns entry?
if testDB is depend on XE service/listener, how i configure OracleServicetestDB to seperate from XE services ?
List item
java/jdbc code:
import java.sql.Connection;
import java.sql.DriverManager;
public class FirstExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
static final String DB_URL = "jdbc:oracle:thin:#localhost:1521:testDB";
// Database credentials
static final String USER = "testDBUser";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
try {
// STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
// STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected.");
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
tnsnames.ora is used for the openers (apps/tools) depending on driver used and somtimes connection settings; the Java driver can handle most cases without tnsnames, see http://docs.oracle.com/cd/E11882_01/java.112/e16548/urls.htm#JJDBC08200 and note that "TNSnames alias" is only one of several options.
Listener is configured in ORAHOME/network/admin/listener.ora and usually the defaults don't require any change. On Windows listener runs as a service (a Windows service, not to be confused with an Oracle service-name!) and starts automatically. On both Unix and Windows you have one listener even if you have multiple database instances/SIDs.
I have a class that gets tables from Sql Server. the class is static, but the variables are not. I want to know if it is OK in Asp net, because I had read not to use static at database in Asp net.
My Class: (There are more functions in the class, I put here one for example)
public static class DataBase
{
public static bool TableChange(string sqlCreate)
{
using (SqlConnection connection = new SqlConnection(Global.ConnectionString))
{
using (var cmd = new SqlCommand(sqlCreate, connection))
{
try
{
connection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Log.WriteLog(ex.Message + "\n" + sqlCreate, ex, HttpContext.Current.Request);
return false;
}
}
}
return true;
}
}
Thanks in advance
What you have read is most probably something to do with this approach:
public static EntityContext Database = new EntityContext();
// or
public static SqlConnection Database = new SqlConnection("...");
Here you store the database connection in a static variable and thus all parallel requests would want to use the same connection which is a very bad approach if it even works at all (it will probably work sort of fine until the page is under load).
You do not have this problem, because in your case only the methods are static, not the variables. Your code follows the recommended path - open connection (retrieve it from the pool), execute query, close the connection (return it to the pool).
I have written a java sftp application based on Jcraft.jsch running on solaris. Each time the application connects to remote host a duplicate entry is done in known_hosts file. Any help on how to stop this. The connection code is as below:
public boolean connect(Properties props) throws JSchException {
FileSystemOptions fso = new FileSystemOptions();
try {
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fso, "no");
session = SftpClientFactory.createConnection(host, port, login.toCharArray(), password.toCharArray(), fso);
Channel channel = session.openChannel("sftp");
channel.connect();
command = (ChannelSftp) channel;
} catch (FileSystemException e) { ...
Thanks