I have a server application connected to a database like this:
Database::Database(QObject *parent) : QObject(parent)
{
db = QSqlDatabase::addDatabase("QPSQL");
db.setHostName("localhost");
db.setDatabaseName("main");
db.setUserName("postgres");
db.setPort(5432);
db.setPassword("zalfon19");
if(!db.open()){
auto problemDialog = new InfoDialog(InfoDialog::Warning, "Baza danych", "Aplikacja napotkała na problem z połączeniem z bazą danych", nullptr, true);
problemDialog->show();
qDebug()<<"There is a problem with database.";
return;
}
qDebug()<<"There is no problem with database.";
QSqlQuery query;
query.exec("truncate active_errors");
}
The client application without necessary changes to explain my situation:
Database::Database(QObject *parent) : QObject(parent)
{
db = QSqlDatabase::addDatabase("QPSQL");
db.setHostName(settings.dbpath.get());
db.setDatabaseName("main");
db.setUserName("postgres");
db.setPort(5432);
db.setPassword("zalfon19");
if(!db.open()){
auto problemDialog = new InfoDialog(InfoDialog::Warning, "Baza danych", "Aplikacja napotkała na problem z połączeniem z bazą danych", nullptr, true);
problemDialog->show();
qDebug()<<"There is a problem with database.";
}
qDebug()<<"There is no problem with database.";
}
My root problem was not the same input data between Pgadmin and Qt.
db = QSqlDatabase::addDatabase("QPSQL");
db.setHostName("localhost");
db.setDatabaseName("main");
db.setUserName("postgres");
db.setPort(5432);
db.setPassword("password");
all this should be the same.
Related
The following code works in System.Data.Sqlite. Recently I switched to Microsoft.Data.Sqlite, it gives error "Microsoft.Data.Sqlite.SqliteException: 'SQLite Error 14: 'unable to open database"
using (var command = _conn.CreateCommand())
{
var qAttach = #"ATTACH DATABASE 'file:C:\mydata\address.db?immutable=1' AS address";
command.CommandText = qAttach;
command.ExecuteNonQuery();
}
I want to create a model in R using a connection to data stored in SQL Server datawarehouse.
I tried to use RevoScaleR library which returned
package RevoScaleR is not available (for R version 3.4.1)
so, I edited the connection string (given on the code below) for ODBC library:
install.packages("RevoScaleR")
#require("RevoScaleR")
if (!require("RODBC"))
install.packages("RODBC")
conn <- odbcDriverConnect(connection="Driver={SQL Server Native Client 11.0}; Server=CZPHADDWH01/DEV; Database=DWH_Staging; trusted_connection=true")
sqlWait <- TRUE;
sqlConsoleOutput <- FALSE;
cc <- RxInSqlServer(connectionString = conn, wait = sqlWait)
rxSetComputeContext(cc)
train_query <- "SELECT TOP(10000) * FROM dim.Contract"
formula <- as.formula("Cosi ~ ContractID + ApprovedLoanAmount + ApprovedLoadDuration")
forest_model <- rxDForest(formula = formula,
data = train_query,
nTree = 20,
maxDepth = 32,
mTry = 3,
seed = 5,
verbose = 1,
reportProgress = 1)
rxDForest_model <- as.raw(serialize(forest_model, connection = conn))
lenght(rxDForest_model)
However:
package 'RODBC' successfully unpacked and MD5 sums checked
The downloaded binary packages are in
C:\Users\sjirak\AppData\Local\Temp\Rtmpqa9iKN\downloaded_packages
Error in odbcDriverConnect(connection = "Driver={SQL Server Native
Client 11.0}; Server=CZPHADDWH01/DEV; Database=DWH_Staging;
trusted_connection=true") : could not find function
"odbcDriverConnect" In library(package, lib.loc = lib.loc,
character.only = TRUE, logical.return = TRUE, : there is no
package called 'RODBC'
Any help would be appreciated.
Looking at the documentation of the ODBC, I see the following functions
odbc-package
dbConnect,OdbcDriver-method
dbUnQuoteIdentifier
odbc
odbc-tables
OdbcConnection
odbcConnectionActions
odbcConnectionIcon
odbcDataType
OdbcDriver
odbcListColumns
odbcListDataSources
odbcListDrivers
odbcListObjects
odbcListObjectTypes
odbcPreviewObject
OdbcResult
odbcSetTransactionIsolationLevel
test_roundtrip
hence I dont see your function in this list. This could be the reason why...
Hence, check the documentation for the proper function.
I'm trying to connect to my local sql server database at my home network using the code that I found from this site Querying SQL Server with Google Apps Script via JDBC about 3 years ago which was marked being correct. However, I get the error message "We're sorry, a server error occurred. Please wait a bit and try again.". This error is from line 2 where the connection string is defined. I retried several times, but I always get the same error. When I searched this error, it seems like it could be too many things and I was not able to find any answers for my issue. Thanks.
This was the code that was marked being correct:
function readAzure() {
var conn = Jdbc.getConnection("jdbc:sqlserver://XYZ.database.windows.net:1433;databaseName=MYDATABSENAME","USERNAME","PASSWORD");
var stmt = conn.createStatement();
var rs = stmt.executeQuery("select * from helloworld");
var doc = SpreadsheetApp.create('azure');
var cell = doc.getRange('a1');
var row = 0;
while(rs.next()) {
cell.offset(row, 0).setValue(rs.getString(1));
cell.offset(row, 1).setValue(rs.getString(2));
row++;
}
rs.close();
stmt.close();
conn.close();
}
I also found another connection string code and when I try this format I get the same error.
var conn = Jdbc.getConnection("jdbc:sqlserver://IP-address:1433;" + "databaseName=DBName;user=username;password=password;");
Based on this documentation, you need to ensure that your database accepts connections from any of Apps Script's IP addresses. These are the address ranges you'll need to whitelist.
64.18.0.0 - 64.18.15.255
64.233.160.0 - 64.233.191.255
66.102.0.0 - 66.102.15.255
66.249.80.0 - 66.249.95.255
72.14.192.0 - 72.14.255.255
74.125.0.0 - 74.125.255.255
173.194.0.0 - 173.194.255.255
207.126.144.0 - 207.126.159.255
209.85.128.0 - 209.85.255.255
216.239.32.0 - 216.239.63.255
Also, from the documentation link above, there is a sample code that you can follow to set up external database via JDBC.
Here is a code that demonstrates how to write a single record to the database as well as a batch of 500 records.
// Replace the variables in this block with real values.
var address = 'database_IP_address';
var user = 'user_name';
var userPwd = 'user_password';
var db = 'database_name';
var dbUrl = 'jdbc:mysql://' + address + '/' + db;
// Write one row of data to a table.
function writeOneRecord() {
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
var stmt = conn.prepareStatement('INSERT INTO entries '
+ '(guestName, content) values (?, ?)');
stmt.setString(1, 'First Guest');
stmt.setString(2, 'Hello, world');
stmt.execute();
}
// Write 500 rows of data to a table in a single batch.
function writeManyRecords() {
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
conn.setAutoCommit(false);
var start = new Date();
var stmt = conn.prepareStatement('INSERT INTO entries '
+ '(guestName, content) values (?, ?)');
for (var i = 0; i < 500; i++) {
stmt.setString(1, 'Name ' + i);
stmt.setString(2, 'Hello, world ' + i);
stmt.addBatch();
}
var batch = stmt.executeBatch();
conn.commit();
conn.close();
var end = new Date();
Logger.log('Time elapsed: %sms for %s rows.', end - start, batch.length);
}
For more information, just read through to this documentation and check this thread and related SO question.
Npgsql v3.0.0-beta0001 (Prerelease) was having below issue while opening connection.
NpgsqlConnection conn = new NpgsqlConnection(#"Server=xx.xx.xx.xx;Port=9996;Database=xxx;User Id=xx;Password=xx;CommandTimeout=40;");
conn.Open();
ex {" : View 'pg_type' not found"} System.Exception {Npgsql.NpgsqlException}
StackTrace " at Npgsql.NpgsqlConnector.DoReadSingleMessage(DataRowLoadingMode dataRowLoadingMode, Boolean returnNullForAsyncMessage)\r\n at Npgsql.NpgsqlConnector.ReadSingleMessage(DataRowLoadingMode dataRowLoadingMode, Boolean returnNullForAsyncMessage)\r\n at Npgsql.NpgsqlConnector.SkipUntil(BackendMessageCode stopAt1, BackendMessageCode stopAt2)\r\n at Npgsql.NpgsqlDataReader.SkipUntil(BackendMessageCode stopAt1, BackendMessageCode stopAt2)\r\n at Npgsql.NpgsqlDataReader.NextResultInternal()\r\n at Npgsql.NpgsqlDataReader.NextResult()\r\n at Npgsql.NpgsqlDataReader.Init()\r\n at Npgsql.NpgsqlCommand.Execute(CommandBehavior behavior)\r\n at Npgsql.NpgsqlCommand.ExecuteDbDataReaderInternal(CommandBehavior behavior)\r\n at Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior)\r\n at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)\r\n at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior)\r\n at Npgsql.TypeHandlerRegistry.LoadBackendTypes(NpgsqlConnector connector)\r\n at Npgsql.TypeHandlerRegistry.Setup(NpgsqlConnector connector)\r\n at Npgsql.NpgsqlConnector.Open()\r\n at Npgsql.NpgsqlConnectorPool.GetPooledConnector(NpgsqlConnection Connection)\r\n at Npgsql.NpgsqlConnectorPool.RequestConnector(NpgsqlConnection connection)\r\n at Npgsql.NpgsqlConnection.Open()\r\n at Test.Program.MssDenodoUpdate(String ssConnectionName, String ssTableName, TestDenodoUpdate ssUpdateRecord, String ssWhereClause, Int32 ssTimeout, Int32& ssUpdatedRows) in d:\EMRP\EMRP\DenodoConnector\Source\ConsoleApplication2\Program.cs:line 66" string
EntityFramework needs a "maintenance" DB in order to create databases, etc.
Before npgsql version 2.2.5. this maintenance DB was "postgres" but, since then this maintenance DB is "template1", which exists on all PostgreSQL versions.
To make EF work with Denodo you have to create in VDP the dummy database called template1.
Hope this helps!
Virtual DataPort is compatible with the .Net Data Provider for PostgreSQL version 2.0. The recommended versions are 2.0.12, 2.2.0, 2.2.3 and 2.2.7 .
I used .netframework 4.5, npgsql version 2.2.0
string query = "SELECT * FROM car";
string connectionString = "Server=localhost;Port=9996;Username=admin;Password=admin;Database=admin;Timeout=300;CommandTimeout=300";
try
{
using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
{
connection.Open();
using (NpgsqlCommand command = new NpgsqlCommand(query, connection))
{
using (DbDataReader reader = command.ExecuteReader())
{
int readRows = 0;
Console.WriteLine();
Console.WriteLine("RESULTS:");
while (reader.Read() && readRows < maxRows)
{
for (int col = 0; col < reader.FieldCount; col++)
{
Console.Write(reader.GetName(col) + "=" + reader[col]);
Console.Write(" ");
}
Console.WriteLine();
readRows++;
}
}
}
}
}
Hello I´ve a problem when I try to monitor which one of a cluster oam servers is online and offline I use the the getServerDiagnosticInfo() method of AccessClient class from aSDK, but the Hashtable that returns only contains Keys (name and port of server) and Values that contains another HashTable (ObKeyMapVal a subtype of HashTable) but I think that this object must contains the health, server port, server name and number of connections as mentioned in the API doc but when I print the size and contents of it only prints "0" and [] (its empty)
snippet:
try{
AccessClient ac = AccessClient.createDefaultInstance("/dir",AccessClient.CompatibilityMode.OAM_10G);
Hashtable info = ac.getServerDiagnosticInfo();
Set<?> servers = info.keySet();
Collection<?> serverInfo = info.values();
System.out.println("Num of servers: " + servers.size());
Iterator it = servers.iterator();
Object servidor = null;
Object dato = null;
while(it.hasNext()){
servidor = it.next();
System.out.println("Server: " + servidor);
dato = info.get(servidor);
System.out.println("Data: " + dato);
ObKeyValMap ob = (ObKeyValMap) dato;
System.out.println("Size: " + ob.keySet().size());
System.out.println("Is Empty: " + ob.keySet().isEmpty());
System.out.println("Properties: " + ob.keySet());
}
ac.shutdown();
} catch (oracle.security.am.asdk.AccessException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
And got the next output:
Num of servers: 2
Server: myserver1.com5575
Data: {}
Size: 0
Is Empty: true
Properties: []
Server: myserver2.com5575
Data: {}
Size: 0
Is Empty: true
Properties: []
Thanks for your help !!!
Once you get the OAM Server Host and Port using getServerDiagnosticInfo(). Try to do telnet ( I am not Java Expert, following link may help How to connect/telnet to SPOP3 server using java (Sockets)?) , if the server is up the telnet session will be established.