I have developed a simple application in Visual studio 2008.Its a combination of C and C++.Now am trying to connect to SQLserver2005.Installed SQlserver2005 managementExpress studio.
Created database and table.To know about the connectivty took a example to insert the data from C code.But its doesnot showing any thing.I know its very simple.But some where am doing wrong.
I would like to clarify few things about the below code.want to do the connectivty locally not server part by using SQLserver2005.
In connection string what username and password i should mention.
what does this line really do."hr = pConn->Open(strCon,"keerth","keerth",0);"
ususally in MYSQL we will create the DNS.but how to mention DNS in SQL server2005.
If i want to insert the variable value(which will display in console window) into database.kindly let me know is it possible? if so suggest me any idea to implement it.
Is there any tutorial links to learn about these things.
#include "stdafx.h"
#import "C:\Program Files\Common Files\System\ADO\msado15.dll" \
no_namespace rename("EOF", "EndOfFile")
int main(int argc, char* argv[])
{
/*The following variables will be initialized with necessary values and appended to the strSQL values*/
_bstr_t strName;
_bstr_t strAge;
_bstr_t strDOB;
_bstr_t strSalary;
_ConnectionPtr pConn = NULL;
// Define string variables for ADO connection
_bstr_t strCon("Provider=SQLOLEDB.1;Persist Security Info=False;Username=keerth;Password=keerth;Initial Catalog=keerth516;Data Source=(local);Integrated Security=SSPI;");
HRESULT hr = S_OK;
//Initialize the COM Library
CoInitialize(NULL);
try
{
//Create the Connection pointer
hr = pConn.CreateInstance((__uuidof(Connection)));
if(FAILED(hr))
{
printf("Error instantiating Connection object\n");
goto cleanup;
}
//Open the SQL Server connection
hr = pConn->Open(strCon,"keerth","keerth",0);
if(FAILED(hr))
{
printf("Error Opening Database object using ADO _ConnectionPtr \n");
goto cleanup;
}
/*Initialize the values */
strName = "'C++ ADO insert Sample',";
strAge = "23,";
strDOB = "'13/04/1988',";
strSalary = "16600.10)";
/* Append the values to the Insert Statement */
_bstr_t strSQL("Insert into Table1(NAME,AGE,DOB,SALARY) Values(");
strSQL += strName + strAge + strDOB + strSalary ;
printf("%s\n",(LPCSTR)strSQL);
//Execute the insert statement
pConn->Execute(strSQL,NULL,adExecuteNoRecords);
printf("Data Added Successfully\n",(LPCSTR)strSQL);
//Close the database
pConn->Close();
}
catch(_com_error &ce)
{
//printf("Error:%s\n",ce.ErrorInfo);
printf("Error:%s\n,",(char*)ce.Description());
}
cleanup:
CoUninitialize();
return 0;
}
You might want to take a look at the ADO API at http://msdn.microsoft.com/en-us/library/windows/desktop/ms678086(v=vs.85).aspx.
I don't think it makes sense to provide username/password as parameters to Open and as parameters in the connection string. Setting "Integrated Security=SSPI" activates integrated windows logon, so this even makes your username/password more redundant. The connectionString is documented in the MSDN (link above), the connection string parts that are specific to the DB providers are documented here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681020(v=vs.85).aspx.
"pConn->Open(strCon,"keerth","keerth",0);" opens the connection to the database server.
3.ususally in MYSQL we will create the DNS.but how to mention DNS in SQL server2005.
What do you mean with this?
4.If i want to insert the variable value(which will display in console window) into database.kindly let me know is it possible? if so suggest me any idea to implement it.
You can use ADO RecordSet with AddNew or the Execute function in your sample. Using Execute you might add adCmdText to the last parameter.
Related
Here is the problem I have met: An ActiveX control in the system of my company needs to connect Database, Oracle 10g in fact, via ADO. It works fine in IE8 of our customers' computers, but after IE8 is upgraded to IE11, it can't connect to database any more. I see no change on the face: connection string is same, codes don't change, Oracle is still the old one. Could any suggest what could possibly cause this problem?
ps: We use ADO2 developed by Carlos Antollini cantollini#hotmail.com.
Thanks for commenting. There is no warning, and I can't even extract error or exception from the program. It runs on win7. The ActiveX is a small control developed by my company years agao. The core code used to connect database is as follow:
strConnection = "Provider=OraOLEDB.Oracle";
strConnection += ";User ID=" + m_sUserName;
strConnection += ";Password=" + m_sPassword;
strConnection += ";Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)";
strConnection += "(HOST="+m_sSQLServerName+")(PORT=1521))";
strConnection += "(CONNECT_DATA=(SERVICE_NAME = " + m_sSQLDBName + ")))";
strConnection += ";Persist Security Info=False";
the strConnection will be used as parameter feeds to the Open() method of _ConnectionPtr object of ADO, the connecting code is like this:
m_pConnection->Open(strConnection , userId, password, NULL);
where m_pConnection a varible of type _ConnectionPtr, a pointer of Connection.
I am pretty sure the userID and password are right.
I guess the connection error might be related to Provider=OraOLEDB.Oracle, like dll missing or registration problem? But I can't be sure, I don't know the underlying mechanism of ADO.
2020.6.22 Add:
I have found the same problem in win10, it seems that is not a problem of IE, msado15 which is unable to connect to database after some update. The database-connection part of the code is:
_ConnectionPtr m_pConnection;
try
{
hr = m_pConnection->Open(_bstr_t(m_strConnection), _bstr_t(lpstrUserID), _bstr_t(lpstrPassword), NULL);
return hr == S_OK;
}
catch(_com_error &e)
{
dump_com_error(e);
return FALSE;
}
It works fine in win7 but throws exception in win10, the exception object gives information as follow:
_com_error &e:
m_hresult = E_FAIL
[0] = 0x536a8590 _com_error::`scalar deleting destructor'(unsigned int)
m_perrinfo = 0x013aaaa0
IUNKOWN
__vfptr = 0x532d120c
[0] = 0x533001e0
[1] = 0x533003c0
[2] = 0x532fedc0
m_pszMsg = 0x00000000 <Bad Ptr>
And the description in the exception object is:
CADODataBase Error
Code = 80004005
Code meaning = undefined error
Source = OraOLEDB
Description = ORA-12154: TNS: unable to resolve given connection identifier
Sorry, If u filling bored. I have searched on several search engines but could not got any result. Anyway I am working in an App which database is mysql. Now I have created a database wrapper class and want to check if the connection is already opened. Could u help me?
String^ constring = L"datasource=localhost;port=3306;username=root;password=pass;database=eps;";
String^ my_query = L"select id from eps_users where usr = '" + this->user_name->Text + "' and psw = md5('" + this->pass_word->Text + "');";
MySqlConnection^ conDatabase = gcnew MySqlConnection(constring);
MySqlCommand^ cmd = gcnew MySqlCommand(my_query, conDatabase);
MySqlDataReader^ myreader;
try
{
conDatabase->Open();
myreader = cmd->ExecuteReader();
int count = 0;
while (myreader->Read())
{
count = count + 1;
}
if (count == 1){
MessageBox::Show("Username And Password is correct.", "Success", MessageBoxButtons::OK,
MessageBoxIcon::Information);
this->Hide();
Form2^ f2 = gcnew Form2(constring);
f2->ShowDialog();
}
else{
MessageBox::Show("Username And Password is not correct.", "Error", MessageBoxButtons::OK,
MessageBoxIcon::Error);
// <del>
this->Hide();
Form2^ f2 = gcnew Form2(constring);
f2->ShowDialog();
// </del>
}
}
catch (Exception^ ex)
{
MessageBox::Show(ex->Message);
}
conDatabase->Close();
I need to check if( conDatabase->HasBeenOpened()) { conDatabase->Open();}
The MySqlConnection type implements a feature called connection pooling that relies on the garbage collector to help recycle connections to your database, such that the best practice with regards to connection objects is to create a brand new object for most calls to the database, so that the garbage collector can correctly recycle the old ones. The process goes like this:
Create a new connection
Open the connection
Use the connection for one query/transaction
Dispose the connection
Where all four steps live within a single try/catch/finally block. (Also, the dispose step needs to happen inside the finally block!) Because you generally start with a brand new connection object, there's not typically a need to check if it's open first: you know it's closed. You also don't need to check the state after calling Open(): the method will block until it's finished, and throw an exception if it fails.
However, if you really are in one of the (rare!) situations where it's a good idea to preserve the connection for an extended period, you can check the state like this:
if( conDatabase->State == ConnectionState::Open)
Now, there is one other issue in that code I'd like to talk about. The issue comes down to this: what do you think will happen if I put the following into your username text box:
';DROP Table eps_users;--
If you think that it will try to execute that DROP statement in your database, you're right: it will! More subtle and damaging queries are possible, as well. This is a huge issue: there are bots that run full time crawling web sites looking for ways to abuse this, and even an corporate internal desktop apps will get caught from time to time. To fix this, you need to use Parameterized Queries for every instance where include user-provided data as part of your sql statement.
A quick example might look like this:
String^ my_query = L"select id from eps_users where usr = #userID;";
MySqlCommand^ cmd = gcnew MySqlCommand(my_query, conDatabase);
cmd->Parameters->AddWithValue(L"#userID", this->user_name->Text);
Hi I have a problem with my Java program, when I run the application within JDeveloper, the program works fine, it connects to the derby database properly.
When I create a executable jar i get the following error no suitable driver found for jdbc:derby://localhost:1527/c:..../dbcam
i have tried the following
{ public void DoConnect3( ) {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
// conenct to the database
// String host ="jdbc:derby://localhost:1527/dbCam";
//String host ="jdbc:derby://localhost:1527/C:/Users/nasir/SkyDrive/Java/db_Backup/dbCam";
String host ="jdbc:derby://localhost:1527/C:/Users/nasir/.netbeans-derby/dbCam";
String uName ="userCam";
String uPass ="cam";
con = DriverManager.getConnection(host,uName,uPass);
stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );
//String sql = "SELECT * FROM tableCustomer";
String sql = "SELECT * FROM tableTroubleshooting";
//String tsss = Integer.toString(tss);
//String sql = "SELECT * FROM tableTroubleshooting where ProbID "+"'"+tsss+"'";
rs = stmt.executeQuery(sql);
rs.next();
}
That still doesn't do much only shows me message saying org.apache.derby.clientdriver.
Any suggestions would be gratefully appreciated.
Thanks
The url you're using is a ClientDriver url, not an EmbeddedDriver url. You need to add the correct jar and load the correct driver.
HTH
D
I got confused with the manual , should i work like this:
{
QSqlDatabase db = QSqlDatabase::addDatabase (...);
QSqlQuery query (db);
query.exec (...);
}
QSqlDatabase::removeDatabase (...);
As the document points out, query or db will be deconstructed automatically.
But is that efficient ?
Well , if i cache db inside a class , like the following:
class Dummy {
Dummy() {
db = QSqlDatabase::addDatabase (...);
}
~Dummy() {
db.close();
}
bool run() {
QSqlQuery query (db);
bool retval = query.exec (...);
blabla ...
}
private:
QSqlDatabase db;
};
Sometimes i could see warnings like:
QSqlDatabasePrivate::removeDatabase: connection 'BLABLA' is still in use, all queries will cease to work.
Even if i didn't call run().
When you create a QSqlDatabase object with addDatabase or when you call removeDatabase, you are merely associating or disassociating a tuple (driver, hostname:port, database name, username/password) to a name (or to the default connection name if you don't specify a connection name). The SQL driver is instantiated, but the database will only be opened when you call QSqlDatabase::open.
That connection name is defined application-wide. So if you call addDatabase in each of the objects that use it, you are changing all QSqlDatabase objects that uses the same connection name and invalidating all queries that were active on them.
The first code example you cited shows how to correctly disassociate the connection name, by ensuring that:
all QSqlQuery are detached from the QSqlDatabase before closing the database by calling QSqlQuery::finish(), which is automatic when the QSqlQuery object goes out of scope,
all QSqlDatabase with the same connection name are close()d when you call QSqlDatabase::removeDatabase (close() is also called automatically when the QSqlDatabase object goes out of scope).
When you create the QSqlDatabase, depending on whether you want the connection to stay open for the application lifetime (1) or just when needed (2), you can:
keep a single QSqlDatabase instance in one single class (for example, in your mainwindow), and use it in other objects that needs it either by passing the QSqlDatabase directly or just the connection name that you pass to QSqlDatabase::database to get the QSqlDatabase instance back. QSqlDatabase::database uses QHash to retrieve a QSqlDatabase from its name, so it is probably negligibly slower than passing the QSqlDatabase object directly between objects and functions, and if you you use the default connection, you don't even have to pass anything anywhere, just call QSqlDatabase::database() without any parameter.
// In an object that has the same lifetime as your application
// (or as a global variable, since it has almost the same goal here)
QSqlDatabase db;
// In the constructor or initialization function of that object
db = QSqlDatabase::addDatabase("QSQLDRIVER", "connection-name");
db.setHostname(...);
// ...
if(!this->db.open()) // open it and keep it opened
{
// Error handling...
}
// --------
// Anywhere you need it, you can use the "global" db object
// or get the database connection from the connection name
QSqlDatabase db = QSqlDatabase::database("connection-name");
QSqlQuery query(db);
configure the QSqlDatabase once, open it to test that the parameters are correct, and ditch the instance. The connection name, will still be accessible anywhere, but the database will have to be reopened:
{
// Allocated on the stack
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLDRIVER", "connection-name");
db.setHostname(...);
// ...
if(!this->db.open()) // test the connection
{
// Error handling
}
// db is closed when it goes out of scope
}
{
// Same thing as for (1), but by default database() opens
// the connection if it isn't already opened
QSqlDatabase db = QSqlDatabase::database("connection-name");
QSqlQuery query(db);
// if there is no other connection open with that connection name,
// the connection is closed when db goes out of scope
}
In that case, note that you shouldn't close the database explicitly, because you can have multiple objects using the same database connection in a reentrant manner (for example, if a function A use the connection and calls B which also use the connection. If B closes the connection before returning control to A, the connection will also be closed for A, which is probably a bad thing).
QSqlDatabase and QSqlQuery are lightweight wrappers around concrete implementations, so your first example is fine. If you provide a name when adding the connection, or use the default database, then simply writing 'QSqlDatabase db(name)' gives you the database object with very little overhead.
removeDatabase is equivalent to closing the file (for sqlite) or the connection (for ODBC/MySql/Postgres), so that's typically something you would do at program termination. As the warning says, you must ensure all database and query objects which refer to that database, have already been destroyed, or bad things can happen.
I find that the instructions have to be run exactly in the order it is below or else you have issues, either with the database connection or query. This works in Qt5.
QSqlQueryModel *model = new QSqlQueryModel;
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(fileName);
if (db.isValid())
{
db.open();
if (db.isOpen())
{
QSqlQuery searchQuery(db);
searchQuery.prepare("SELECT * FROM myTable");
searchQuery.exec();
if(searchQuery.isActive())
{
model->setQuery(searchQuery);
sui->DBDisplay->setModel(model);
db.close();
} else {
qDebug() << "query is not active";
}
} else {
qDebug() << "DB is not open";
}
} else {
qDebug() << "DB is not valid";
}
How i could check if i have connection to an SQL Server with the Connection String known in C#?
using (var connection = new SqlConnection("connectionString"))
{
try
{
connection.Open();
Console.WriteLine("Connection Ok");
}
catch (SqlException)
{
Console.WriteLine("Connection Not Ok");
}
}
I"m not sure if you are asking how to validate a connection string or check to see if a current connection is open If you are trying to check if a current connection is open you can use.
connection.State
ConnectionState Enumeration Values
You can also test it outside of your code by making an UDL file (a text file with extension .UDL). Then right-click it, get the properties and enter the connectionstring details.
Press the "Test Connection" button and then you'll know.
Check the state of the connection.
if (conexion.State == ConnectionState.Closed)
{
conexion.Open();
}