I have the below C# and Entity framework 6.4 code to get data from
postgresql function
return Database.SqlQuery<TEntity>(sql, parameters).ToArrayAsync();
and I tried
var sql = $#"select * from GetLogs(?,?,?,?,?,?,?,?,?,?,?,?,?)"; or
var sql = $#"select * from GetLogs($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)";
but got failed, anybody know about it?
I also try
var sql = "select * from GetLogs(TO_TIMESTAMP({0},'YYYY-MM-DD HH24:MI:SS'), TO_TIMESTAMP({1},'YYYY-MM-DD HH24:MI:SS'),{2},'{3}','{4}',{5},'{6}','{7}',{8},{9},{10})";
var from = request.From.ToString("yyyy-MM-dd HH:mm:ss");
var to = request.To.ToString("yyyy-MM-dd HH:mm:ss");
return Database.SqlQuery<AdminLogMasterModel>(sql,
from,
to,
request.HttpStatusCode,
request.ServerName,
request.Page,
request.TrackingId,
request.Content,
request.SortBy,
request.OrderBy == SortOrder.Ascending ? 0 : 1,
request.Page,
request.Rows).ToArrayAsync();
This got no error but no date return. It seems postgresql didn't pass parameter in EF.
I tried the below code can work
var sql = "select * from GetLogs(TO_TIMESTAMP(#p0,'YYYY-MM-DD HH24:MI:SS'),TO_TIMESTAMP(#p1,'YYYY-MM-DD HH24:MI:SS'),#p2,#p3,#p4,#p5,#p6,#p7,#p8,#p9,#p10)";
var para = new NpgsqlParameter[]
{
new NpgsqlParameter("#p0", request.From.ToString("yyyy-MM-dd HH:mm:ss")),
new NpgsqlParameter("#p1", request.To.ToString("yyyy-MM-dd HH:mm:ss")),
new NpgsqlParameter("#p2", CreateRequestValueifNull(request.HttpStatusCode)),
new NpgsqlParameter("#p3", CreateRequestValueifNull(request.ServerName)),
new NpgsqlParameter("#p4", CreateRequestValueifNull(request.Path)),
new NpgsqlParameter("#p5", CreateRequestValueifNull(request.TrackingId)),
new NpgsqlParameter("#p6", CreateRequestValueifNull(request.Content)),
new NpgsqlParameter("#p7", request.SortBy),
new NpgsqlParameter("#p8", request.OrderBy == SortOrder.Ascending ? 0 : 1),
new NpgsqlParameter("#p9", request.Page),
new NpgsqlParameter("#p10", request.Rows),
};
return Database.SqlQuery<LogModel>(sql, para).ToArrayAsync();
A restore performed with C# code using SMO objects restores fine when original database is in SIMPLE recovery mode. We got problems with one database where the restore missed all content from a certain table, where all data was inserted late in process. The database showed to be in BULK LOGGED recovery mode. After changing to SIMPLE and doing a new backup, it restored fine, using our code.
We have tried different settings on the restore object, but found none that fixes the problem. We are under the impression that the restoring ignores data in the log.
The basic restore looks like this:
sqlServer = new Server(new ServerConnection(instanceName));
restore = GetRestore();
restore.PercentComplete += PercentCompleteAction;
restore.Complete += CompleteAction;
restore.SqlRestore(sqlServer);
the GetRestore function is basically implemented like this:
restore = new Restore();
var deviceItem = new BackupDeviceItem(backupFileName, DeviceType.File);
restore.Devices.Add(deviceItem);
restore.Database = newDatabaseName;
restore.NoRecovery = false;
restore.Action = RestoreActionType.Database;
restore.ReplaceDatabase = false;
return restore;
There are no error messages - just missing content in one table.
Added try:
I took a guess at the solution below, but it didn't help:
restore.ReplaceDatabase = false;
restore.NoRecovery = true;
restore.Action = RestoreActionType.Database;
restore.SqlRestore(sqlServer);
restore.ReplaceDatabase = true;
restore.NoRecovery = true;
restore.Action = RestoreActionType.Log;
restore.SqlRestore(sqlServer);
restore.ReplaceDatabase = true;
restore.NoRecovery = false;
restore.Action = RestoreActionType.Files;
restore.SqlRestore(sqlServer);
You need select a correct FileNumber in your Log file, see this method can solve your problem:
public static void restaurarBackup(string pathFileBak)
{
SqlConnection conn = new SqlConnection(Connection.getCon());
Server smoServer = new Server(new ServerConnection(conn));
string localFilePath = pathFileBak;
string db_name = "ETrade";
string defaultFolderEtrade = #"C:\ETrade\";
Restore rs = new Restore();
rs.NoRecovery = false;
rs.ReplaceDatabase = true;
BackupDeviceItem bdi = default(BackupDeviceItem);
bdi = new BackupDeviceItem(localFilePath, DeviceType.File);
rs.Devices.Add(bdi);
DataTable dt = rs.ReadFileList(smoServer);
foreach (DataRow r in dt.Rows)
{
string logicalFilename = r.ItemArray[dt.Columns["LogicalName"].Ordinal].ToString();
string physicalFilename = defaultFolderEtrade + Path.GetFileName(r.ItemArray[dt.Columns["PhysicalName"].Ordinal].ToString());
rs.RelocateFiles.Add(new RelocateFile(logicalFilename, physicalFilename));
}
DataTable backupHeaders = rs.ReadBackupHeader(smoServer);
rs.FileNumber = Convert.ToInt32(backupHeaders.AsEnumerable().Max(backupInfo => backupInfo["Position"]));
rs.Database = db_name;
smoServer.KillAllProcesses(rs.Database);
Microsoft.SqlServer.Management.Smo.Database db = smoServer.Databases[rs.Database];
db.DatabaseOptions.UserAccess = DatabaseUserAccess.Single;
rs.SqlRestore(smoServer);
db = smoServer.Databases[rs.Database];
db.SetOnline();
smoServer.Refresh();
db.Refresh();
}
If you want look backups in your Log file, see this query:
SELECT database_name, name, backup_start_date,
backup_finish_date, datediff(mi, backup_start_date, backup_finish_date) [tempo (min)],
position, first_lsn, last_lsn, server_name, recovery_model,
type, cast(backup_size/1024/1024 as numeric(15,2)) [Tamanho (MB)], B.is_copy_only
FROM msdb.dbo.backupset B
I want to establish a connection to MS SQL in Google docs via Script by using integrated security = SSIP, basically connecting to the server with my integrated Windows authentication. However, Google tells me that the 'integrated security' connection property is unsupported. I tried phrasing it differently (trusted_security etc.) but nothing works.
Does anyone know a workaround?
I used the query google offered below.
// 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' integrated security = ssip;
// Read up to 1000 rows of data from the table and log them.
function readFromTable() {
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
var start = new Date();
var stmt = conn.createStatement();
stmt.setMaxRows(1000);
var results = stmt.executeQuery('SELECT * FROM entries');
var numCols = results.getMetaData().getColumnCount();
while (results.next()) {
var rowString = '';
for (var col = 0; col < numCols; col++) {
rowString += results.getString(col + 1) + '\t';
}
Logger.log(rowString)
}
results.close();
stmt.close();
var end = new Date();
Logger.log('Time elapsed: %sms', end - start);
}
I am inserting data in the sql server.Here is the code:
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter();
param[0].ParameterName = "#Exch";
param[0].SqlDbType = SqlDbType.Int;
param[0].Value = "BSE";
formObjSqlConnection.SQLConnection.Executes("LPExch..DeleteVarMargin", param);
foreach (BseVar objBseVar in objListNseData)
{
currentIndex++;
param = new SqlParameter[10];
param[0] = new SqlParameter();
param[0].ParameterName = "#Exch";
param[0].SqlDbType = SqlDbType.Char;
param[0].Value = "BSE";
param[1] = new SqlParameter();
param[1].ParameterName = "#Symbol";
param[1].SqlDbType = SqlDbType.Char;
param[1].Size = 10;
param[1].Value = objBseVar.Symbol;
param[2] = new SqlParameter();
param[2].ParameterName = "#Series";
param[2].SqlDbType = SqlDbType.Char;
param[2].Value = "EQ";
param[3] = new SqlParameter();
param[3].ParameterName = "#SecurityVar";
param[3].SqlDbType = SqlDbType.SmallMoney;
param[3].Value = objBseVar.SecurityVar;
param[4] = new SqlParameter();
param[4].ParameterName = "#IndexVar";
param[4].SqlDbType = SqlDbType.SmallMoney;
param[4].Value = 0;
param[5] = new SqlParameter();
param[5].ParameterName = "#VarMargin";
param[5].SqlDbType = SqlDbType.SmallMoney;
param[5].Value = objBseVar.IndexVar;
param[6] = new SqlParameter();
param[6].ParameterName = "#AdhocMargin";
param[6].SqlDbType = SqlDbType.SmallMoney;
param[6].Value = objBseVar.SecurityVar - objBseVar.IndexVar;
param[7] = new SqlParameter();
param[7].ParameterName = "#VarMarginRate";
param[7].SqlDbType = SqlDbType.SmallMoney;
param[7].Value = objBseVar.IndexVar;
formObjSqlConnection.SQLConnection.Executes("LPExch..UpdateOrAddCashVarMarginBSE", param);
if (Convert.ToInt32(1 / progressChange * currentIndex) <= 100)
objImportMaster.UpdateProgressBar(Convert.ToInt32(1 / progressChange * currentIndex));
}
formObjSqlConnection.SQLConnection.Executes("LPExch..UpdateCashVarMarginBSEScripNo");
Is there any other way i can insert the data in the database.The problem is that database is taking too much time to insert the data.Also i am updating the progressbar in other UI.
Is that the reason for slow insertion?
Can we use any other way to insert data.?
Right now you are sending every insert one at a time. That's slow. If you can change the database, look up table valued parameters and pass a table to your function so you can send all the records just once.
If you have direct access to a table, you can also use bulk copy.
If you are trying to insert many records then consider using bulk copy, it is quite fast.
An example is available here.
Hypothetically, is it better to send N statements to Sql Server (2008), or is it better to send 1 command comprising N statements to Sql Server? In either case, I am running the same statement over a list of objects, and in both cases I would be using named parameters. Suppose my use case is dumping a cache of log items every few hours.
foreach example
var sql = "update blah blah blah where id = #id";
using(var conn = GetConnection())
{
foreach(var obj in myList)
{
var cmd = new SqlCommand()
{CommandText = sql, Connection = conn};
//add params from obj
cmd.ExecuteNonQuery();
}
}
batch example
var sql = #"
update blah blah blah where id = #id1
update blah blah blah where id = #id2
update blah blah blah where id = #id3
-etc";
using (var conn = GetConnection())
{
var cmd = new SqlCommand
{ CommandText = sql, Connection = conn};
for(int i=0; i<myList.Count; i++)
{
//add params: "id" + i from myList[i]
}
cmd.ExecuteNonQuery();
}
In time tests, the batch version took 15% longer than the foreach version for large inputs. I figure the batch version takes longer to execute because the server has to parse a huge statement and bind up to 2000 parameters. Supposing Sql Server is on the LAN, is there any advantage to using the batch method?
Your tests would seem to have given you the answer however let me add another. It is preferrable to encapsulate the update into a separate function and call that using a foreach:
private function UpdateFoo( int id )
{
const sql = "Update Foo Where Id = #Id";
using ( var conn = GetConnection() )
{
using ( var cmd = new SqlCommand( sql, conn ) )
{
cmd.AddParameterWithValue( "#Id", id )
cmd.ExecuteNonQuery();
}
}
}
private function UpdateLotsOfFoo()
{
foreach( var foo in myList )
{
UpdateFoo( foo.Id );
}
}
In this setup you are leveraging connection pooling which mitgates the cost of opening and closing connections.
#Thomas - this design can increase overhead of opening / closing connections in a loop. This is not a preferred practice and should be avoided. The code below allows the iteration of the statements while using one connection and will be easier on resources (both client and server side).
private void UpdateFoo(int id)
{
const string sql = "Update Foo Where Id = #Id";
using (var conn = GetConnection())
{
conn.Open();
foreach (var foo in myList)
{
UpdateFoo(foo.Id);
using (var cmd = new SqlCommand(sql, conn))
{
cmd.AddParameterWithValue("#Id", id);
cmd.ExecuteNonQuery();
}
}
conn.Close();
}
}