Linq DataContext.Log - logging sql command with parameters - linq-to-sql

I using Linq DataContext.Log and I want to save sql command with parameters. how may I do this??
Now to log is writing:
SELECT [t0].[Id_User],
[t0].[FirstName], [t0].[LastName],
[t0].[UserName], [t0].[Password],
[t0].[District_Id], [t0].[Active],
[t0].[MobileDevice_Id],
[t0].[IsMobile], [t0].[IsWWW],
[t0].[IsWholesaler], [t0].[Acc_Admin],
[t0].[Warehouse_Id], [t0].[PIN],
[t0].[ValidFrom], [t0].[ValidTo],
[t0].[IsExternal], [t0].[UserType],
[t0].[DefaultDepartment_Id],
[t0].[Code], [t0].[RowsOnPage],
[t0].[ClientGroup_Id],
[t0].[ClientGroup2_Id],
[t0].[ServerHash],
[t0].[CanOrderInPacks], [t0].[Email],
[t0].[IsAdmin],
[t0].[HasAccessToAllInferiorsData],
[t0].[IsSupplier], [t0].[Position],
[t0].[syncstamp] AS [Syncstamp],
[t0].[Source], [t0].[Deleted],
[t0].[DefaultClient_Id] FROM
[dbo].[Users] AS [t0] WHERE
([t0].[UserName] = #p0) AND
([t0].[Deleted] = #p1)
I want write #p0 and #p1 to log

Param value can be read by following line of code
var results = db.calltodatabase.Where(pradicate);
IQueryable query = results;
DbCommand dbCommand = dataContext.GetCommand(query);
var result = new SqlQueryText();
result.Text = dbCommand.CommandText;
int nParams = dbCommand.Parameters.Count;
result.Params = new ParameterText[nParams];
for (int j = 0; j < nParams; j++)
{
var param = new ParameterText();
DbParameter pInfo = dbCommand.Parameters[j];
param.Name = pInfo.ParameterName;
param.SqlType = pInfo.DbType.ToString();
object paramValue = pInfo.Value;
if (paramValue == null)
{
param.Value = null;
}
else
{
param.Value = pInfo.Value.ToString();
}
result.Params[j] = param;
}

Related

Please I am trying to create a proc or function that will loop over databases in snowflake and return all tables with empty rows

**I was helped with this code in my earlier post but it still did not work, instead it returns the default snowflake table like 7 times on one call.**
create or replace procedure FIND_EMPTY_TABLES(DATABASE_PATTERN string)
returns variant
language javascriptexecute as owner as $$ class Account {constructor(databases){this.databases = databases;}} class Database {constructor(name) {this.name = name;}} class Query{constructor(statement){this.statement = statement;}} var account = getDatabasesInAccount(DATABASE_PATTERN); var out = []; for (var i = 0; i < account.databases.length; i++) { out = out.concat(rsToJSON(getQuery(select TABLE_NAME, TABLE_CATALOG, TABLE_SCHEMA, TABLE_OWNER,ROW_COUNT
from ${account.databases[i].name}.INFORMATION_SCHEMA.TABLES
where TABLE_TYPE = 'BASE TABLE' and ROW_COUNT = 0))); } return out; //------ function getQuery(sql){ cmd1 = {sqlText: sql}; var query = new Query(snowflake.createStatement(cmd1)); query.resultSet = query.statement.execute(); return query; } function executeSingleValueQuery(columnName, queryString) { cmd = {sqlText: queryString}; stmt = snowflake.createStatement(cmd); var rs; rs = stmt.execute(); rs.next(); return rs.getColumnValue(columnName); } function getDatabasesInAccount(databasePattern){ const SYSTEM_DB_NAMES = ["SNOWFLAKE", "SNOWFLAKE_SAMPLE_DATA"]; var db = executeSingleValueQuery("name", "show databases"); var i = 0; var dbRS = getResultSet(select DATABASE_NAME from "${db}".INFORMATION_SCHEMA.DATABASES
where rlike (DATABASE_NAME, '${databasePattern}');`);
var databases = [];
var db;
while (dbRS.next()){
db = new Database(dbRS.getColumnValue("DATABASE_NAME"));
if (!SYSTEM_DB_NAMES.includes(db)) {
databases.push(db);
}
}
return new Account(databases);
}
function getResultSet(sql){
let cmd = {sqlText: sql};
let stmt = snowflake.createStatement(cmd);
let rs = stmt.execute();
return rs;
}
function rsToJSON(query) {
var i;
var row = {};
var table = [];
while (query.resultSet.next()) {
for(col = 1; col <= query.statement.getColumnCount(); col++) {
row[query.statement.getColumnName(col)] = query.resultSet.getColumnValue(col);
}
table.push(row);
}
return table;
}
$$;
All you need to do is read the SNOWFLAKE.ACCOUNT_USAGE.TABLES view where ROW_COUNT = 0
You can make use of the ACCOUNT_USAGE view TABLES:
https://docs.snowflake.com/en/sql-reference/account-usage/tables.html
SELECT TABLE_CATALOG, TABLE_NAME
FROM "SNOWFLAKE"."ACCOUNT_USAGE"."TABLES"
WHERE ROW_COUNT = 0
But you should be aware that there could be some latency.
This is a duplicate of proc or function that will loop over each database in snowflake and list tables with empty rows and I wrote a stored procedure there to do this.

My prepared statement not specified

I am doing a query to the database prepared statement but its just not coming out right.
i get this error when I print my statement.
com.mysql.jdbc.JDBC42PreparedStatement#157b62f9: SELECT * FROM 2015-wind WHERE TimeStamp BETWEEN '2015-01-01' AND '2015-01-25' AND ConnectingArea IN (** NOT SPECIFIED **)
10YAT-APG--L (I print my string and it give me an output).
Anybody knows whats going on here ?
public List<Wind2015> getResultsWind(String beginDate1, String endDate1, String[] connectingAreas1) throws Exception{
int count = 0;
List<Wind2015> myWind2015s = new ArrayList<>();
SimpleDateFormat readFormat = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",
Locale.ENGLISH);
Date date2 = readFormat.parse(beginDate1);
Date date3 = readFormat.parse(endDate1);
String beginDate = new SimpleDateFormat("yyyy-MM-dd").format(date2);
String endDate = new SimpleDateFormat("yyyy-MM-dd").format(date3);
ArrayList<String> connectingArea = new ArrayList<>(Arrays.asList(connectingAreas1));
StringBuilder inputs = new StringBuilder();
for (int i = 0; i < connectingArea.size(); i++) {
if (i < connectingArea.size()-1) {
inputs.append("?,");
} else {
inputs.append("?");
}
}
String connectingAreaInputs = inputs.toString();
Connection connection = null;
PreparedStatement prepareStatement = null;
ResultSet myRs = null;
System.out.println(connectingAreaInputs);
try {
connection = getConnection();
String sql = "SELECT * FROM `2015-wind` WHERE `TimeStamp` BETWEEN ? AND ? AND `ConnectingArea` IN ("+ connectingAreaInputs +")";
prepareStatement = connection.prepareStatement(sql);
prepareStatement.setString(count+=1,beginDate);
prepareStatement.setString(count+=1, endDate);
System.out.println(prepareStatement);
for (String string : connectingArea) {
System.out.println(string);
count+=1;
prepareStatement.setString(count, string);
}
myRs = prepareStatement.executeQuery();
Wind2015 wind2015 = null;
while (myRs.next()) {
String timeStamp = myRs.getString("Timestamp");
String connectingArea1 = myRs.getString("ConnectingArea");
String value = myRs.getString("ActualWindEnergy");
wind2015 = new Wind2015(timeStamp, value, connectingArea1);
myWind2015s.add(wind2015);
}
return myWind2015s;
} finally {
close(connection, prepareStatement, myRs);
}
}
You're printing the prepared statement with this line:
System.out.println(prepareStatement);
before you assign value(s) to the dynamic placeholders in the IN (...) expression, so they're (correctly) displaying as "not [yet] specified".
Move the print statement to after the for loop that it currently sits before.

Java DB select specific column on specific row

First post ever here :) looking franticly for help.
What I'm trying to do is to retrieve a specific image stored as blob in my database. I can't figure out why this query is not executing, I'm getting an exception as soon as I reach the executeQuery statement.
My table is:
Name xcoordinate ycoordinate vista
firstscree 0 0 imag
secondscreen 0 1 img2
... etc.
ResultSet rs = null;
Statement stmnt = null;
Connection con = null;
String host = ...
String unm = ...
String pswrd = ...
BufferedImage imgt = null;
InputStream fis = null;
int xcoord;
int ycoord;
int newcoord;
String SQLNorth = "select vista from location where xcoordinate = "+xcoord+" and ycoordinate = "+newcoord;
newcoord = ycoord + 1;
System.out.println("New coord x and y are" + xcoord + newcoord);
con = DriverManager.getConnection(host, unm, pswrd);
stmnt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = stmnt.executeQuery(SQLNorth);
rs.next();
fis = rs.getBinaryStream(1);
imgt = javax.imageio.ImageIO.read(fis);
Image newImg = SwingFXUtils.toFXImage(imgt, null);
img_1.setImage(newImg);
My guess is that it has something to do with the way you're building the query. Try using a prepared statement instead.
ResultSet rs = null;
PreparedStatement stmnt = null;
Connection con = null;
String host = ...
String unm = ...
String pswrd = ...
BufferedImage imgt = null;
InputStream fis = null;
int xcoord;
int ycoord;
int newcoord;
String SQLNorth = "select vista from location where xcoordinate = ? and ycoordinate = ?";
newcoord = ycoord + 1;
System.out.println("New coord x and y are" + xcoord + newcoord);
con = DriverManager.getConnection(host, unm, pswrd);
stmnt = con.prepareStatement(SQLNorth);
stmnt.setInt(1, xcoord);
stmnt.setInt(2, newcoord);
rs = stmnt.executeQuery(SQLNorth);
rs.next();
fis = rs.getBinaryStream(1);
imgt = javax.imageio.ImageIO.read(fis);
Image newImg = SwingFXUtils.toFXImage(imgt, null);
img_1.setImage(newImg);

Passing parameters to IdbCommand for mySQL database

I am trying to do something relatively simple using IdbCommand to execute an insert query.
Here's the code:
using (IDbConnection conn = DbHelper.GetConnection(DbConnString))
using (IDbCommand com = conn.CreateCommand())
{
com.CommandType = CommandType.Text;
com.CommandText =
String.Format(
"INSERT INTO {0} (`Date`, User, Type, `Comment`) VALUES (#Date, #User, #Type, #Comment);",
TableName);
conn.Open();
var parameterDate = com.CreateParameter();
parameterDate.ParameterName = "#Date";
parameterDate.Value = entry.Date;
parameterDate.DbType = DbType.DateTime;
com.Parameters.Add(parameterDate);
var parameterUser = com.CreateParameter();
parameterUser.ParameterName = "#User";
parameterUser.Value = entry.User;
parameterUser.DbType = DbType.String;
com.Parameters.Add(parameterUser);
var parameterLogType = com.CreateParameter();
parameterLogType.ParameterName = "#Type";
parameterLogType.Value = entry.Type;
parameterLogType.DbType = DbType.Int32;
com.Parameters.Add(parameterLogType);
var parameterComment = com.CreateParameter();
parameterComment.ParameterName = "#Comment";
parameterComment.Value = entry.Comment;
parameterComment.DbType = DbType.String;
com.Parameters.Add(parameterComment);
com.ExecuteNonQuery();
But I keep getting a MySqlException with the message "Column 'Date' cannot be null".
All my selects work fine, it's just this insert that has a problem and I can't see an obvious problem with it.
The parameter is populated with a valid DateTime during runtime.
I thought it might be related to the fact that Date is a reserved word and needs backquotes, but that's what online tutorials recommend.
Any ideas?
Found it!
For some reason instead of #, it needs ?
So the working code is:
using (IDbConnection conn = DbHelper.GetConnection(DbConnString))
using (IDbCommand com = conn.CreateCommand())
{
com.CommandType = CommandType.Text;
com.CommandText =
String.Format(
"INSERT INTO {0} (`Date`, User, Type, `Comment`) VALUES (?Date, ?User, ?Type, ?Comment);",
TableName);
conn.Open();
var parameterDate = com.CreateParameter();
parameterDate.ParameterName = "?Date";
parameterDate.Value = entry.Date;
parameterDate.DbType = DbType.DateTime;
com.Parameters.Add(parameterDate);
var parameterUser = com.CreateParameter();
parameterUser.ParameterName = "?User";
parameterUser.Value = entry.User;
parameterUser.DbType = DbType.String;
com.Parameters.Add(parameterUser);
var parameterLogType = com.CreateParameter();
parameterLogType.ParameterName = "?Type";
parameterLogType.Value = entry.Type;
parameterLogType.DbType = DbType.Int32;
com.Parameters.Add(parameterLogType);
var parameterComment = com.CreateParameter();
parameterComment.ParameterName = "?Comment";
parameterComment.Value = entry.Comment;
parameterComment.DbType = DbType.String;
com.Parameters.Add(parameterComment);
com.ExecuteNonQuery();
}

How to write Linq-To-SQL statment which is equal to my following TSQL?

TSQL:-
Update table1
Set Name = 'John',
Address = null
where
ID = 1
LINQ-TO-SQL
var tab = db.Table1.Single(s => s.ID == 3);
tab.Name = DateTime.Now;
tab.Address = null;
db.SubmitChanges();
There isn't a single LINQ to SQL statement for updates. You have to retrieve the object, modify it, then save the changes (code assumes a single row since you have a specific Id):
var entity = context.Table1.Single(t => t.Id == 1);
entity.Name = "John";
entity.Address = "Toronto";
context.SubmitChanges();
using (var dataContext = new MyEntities())
{
var contact = Contacts.Single (c => c.ContactID == 1);
contact.FirstName = 'John';
contact.Address= 'Toronto';
dataContext.SaveChanges();
}