I want to update a record. But every time i tried to update. It goes to catch statement. I am unable to find that where my query syntax is invalid.
It always goes to catch statement
I have no idea that either the query is wrong or any error is in the syntax.
if (IsPost) {
var value = Request.Form["value"];
var Student_Reg_No = Request.Form["Student_Reg_No"];
var Student_Name = Request.Form["Student_Name"];
var Father_Name = Request.Form["Father_Name"];
var Temporary_Address = Request.Form["Temporary_Address"];
var Permanent_Address = Request.Form["Permanent_Address"];
var Phone_No = Request.Form["Phone_No"];
var Blood_Group = Request.Form["Blood_Group"];
var Email_Address = Request.Form["Email_Address"];
if (Validation.IsValid()){
try{
var db = Database.Open("site_data");
var updateCommand = "Update site_data_table set Student_Reg_No =#0, Student_Name=#1, Father_Name=#2, Temporary_Address=#3,Permanent_Address=#4, Phone_No=#5, Blood_Group=#6, Email_Address=#7 where Id=#8)";
db.Execute(updateCommand, Student_Reg_No, Student_Name, Father_Name, Temporary_Address, Permanent_Address, Phone_No, Blood_Group, Email_Address, value);
Response.Redirect("~/edit?id=success");
}
catch{
<textarea>Data is Not updated</textarea>
}
}
}
var updateCommand = "Update site_data_table set Student_Reg_No =#0, Student_Name=#1, Father_Name=#2, Temporary_Address=#3,Permanent_Address=#4, Phone_No=#5, Blood_Group=#6, Email_Address=#7 where Id=#8)";
Change to
var updateCommand = "Update site_data_table set Student_Reg_No =#0, Student_Name=#1, Father_Name=#2, Temporary_Address=#3,Permanent_Address=#4, Phone_No=#5, Blood_Group=#6, Email_Address=#7 where Id=#8";
Related
**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.
I am having the following JavaScript Procedure:
CREATE PROCEDURE ADD_OBSERVATION_VALUES()
RETURNS string
LANGUAGE JAVASCRIPT
AS
$$
arr = [];
// Get number of rows
//var query = "SELECT COUNT(*) FROM #ingest_stg/load (file_format => 'csv_format', pattern => '.*[.]csv.gz') t";
var query = "SELECT * FROM IYCF_TEMP";
var stmt = snowflake.createStatement( {sqlText: query} );
var rows_result = stmt.execute();
// rows_result.next();
// num_rows = rows_result.getColumnValue(1);
var row_num = 1;
var record_source = 'ONA'
// Set the indicators
COLUMN_FIELD_NAMES = ['beneficiary',
'nbr_1st_cons_6mc_iycfc number',
'followup_2nd_time_6mc_iycfc'];
while(rows_result.next()){
for (var col_num = 0; col_num<COLUMN_FIELD_NAMES.length; col_num = col_num+1){
var col_name = COLUMN_FIELD_NAMES[col_num];
var query = "INSERT INTO LINK_OBSERVATION_FIELD(FIELD_NAME_OBSERVATION_HASH_KEY, LOAD_DT, RECORD_SRC, OBSERVATION_DATE_LOCATION_HASH_KEY, INDICATOR_HASH_KEY)"
query += "VALUES (md5(concat(COLUMN_FIELD_NAMES[col_num], rows_result['date'])), current_timestamp(), record_source, md5(rows_result['date']), md5(COLUMN_FIELD_NAMES[col_num]))";
var stmt = snowflake.createStatement( {sqlText: query} );
if(stmt.execute()){
var query = "INSERT INTO SAT_FIELD_VALUES(OBSERVATION_FIELD_HASH_KEY, LOAD_DT, LOAD_END_DT, record_src, FIELD_VALUE, REVIEW_STATUS, SUBMISSION_DT, FIELD_NAME_OBSERVATION_HASH_KEY)"
query += "VALUES (md5(md5(concat(rows_result[col_name], rows_result['date']))),current_timestamp(), NULL, record_source, rows_result[col_name], 'PENDING', rows_result['_submission_time'], md5(concat(rows_result[col_name], rows_result['date'])))";
var stmt = snowflake.createStatement( {sqlText: query });
stmt.execute()
}
}
}
return "DONE"
$$;
It will loop over a specific field names of a survey to add them with some changes into specific tables on Snowflake.
I am keep getting the following error:
Execution error in store procedure ADD_OBSERVATION_VALUES: SQL compilation error: error line 1 at position 163 invalid identifier 'COLUMN_FIELD_NAMES' At Statement.execute, line 33 position 20
COLUMN_FIELD_NAMES seems to be a variable defined in JS:
// Set the indicators
COLUMN_FIELD_NAMES = ['beneficiary', ...
But then the code uses it as a literal string while building a query:
query += "VALUES (md5(concat(COLUMN_FIELD_NAMES[col_num], ...
Instead, it should be parsed and concatenated with JavaScript and, as in:
query += "VALUES (md5(concat(" + COLUMN_FIELD_NAMES[col_num] +", ...
If executing the query doesn't work, try printing the value instead of executing it, and then debug.
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();
}
I am trying to write a query to show all records owned by the current logged on user but i am having issues inserting the "userid" variable into the string?
#{
Layout = "~/_template1.cshtml";
var db = Database.Open("StayInFlorida");
var userid = WebSecurity.CurrentUserId;
var premierproperty = "SELECT PropertyName, PropertyID FROM PropertyInfo WHERE OwnerID='userid'";
}
<h1>Properties - Page coming soon</h1>
#userid
#foreach (var row in db.Query(premierproperty)){
#row.propertyname
}
Any ideas?
Try like this:
#{
Layout = "~/_template1.cshtml";
var db = Database.Open("StayInFlorida");
var userid = WebSecurity.CurrentUserId;
var premierproperty = "SELECT PropertyName, PropertyID FROM PropertyInfo WHERE OwnerID = #0";
}
<h1>Properties - Page coming soon</h1>
#userid
#foreach (var row in db.Query(premierproperty, userid))
{
#row.propertyname
}
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();
}