SQL - MVC - Insert into 2 tables - mysql

im working in mvc and use sql command to insert data to my
database.
what i try to do is insert into 2 tables which one of them
have the foreign key from the other.
how can i build my sql query to make a condition on insert
into the table Image, insert the id in the foreignkey column
in the table Content.
using (SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
SqlCommand cmd;
System.Text.StringBuilder sql = new System.Text.StringBuilder();
sql.Append("insert into Image(FileName)");
sql.Append("values (#FileName)");
SqlCommand cmd2;
System.Text.StringBuilder sql2 = new System.Text.StringBuilder();
sql.Append("insert into Code(Html,JsCode,Id_Img)");
sql.Append("values (#Html, #JsCode, #Id_Img)");
cn.Open();
cmd = new SqlCommand(sql.ToString(), cn);
cmd.Parameters.Add("#FileName", SqlDbType.VarChar).Value = myfilename;
int FileId = (int)cmd.ExecuteScalar();
cmd2 = new SqlCommand(sql2.ToString(), cn);
cmd2.Parameters.Add("#Html", SqlDbType.VarChar).Value = mydiv;
cmd2.Parameters.Add("#JsCode", SqlDbType.VarChar).Value = DBNull.Value;
cmd2.Parameters.Add("#Id_Img", SqlDbType.Int).Value = FileId;
cmd2.ExecuteNonQuery();
cn.Close();
}

I think you can use ExecuteScalar() instead ExecuteNonQuery() to get the Scope_identity() value from the server like below and add that FileId to the second query.
using (SqlConnection cn = new SqlConnection("your_connection_string"))
{
string sql1 = "insert into Image(FileName) values (#FileName); " +
"SELECT CAST(scope_identity() AS int)";
string sql2 = "insert into Code(Html,JsCode,Id_Img) values (#Html, #JsCode, #Id_Img)";
int FileId = 0;
using (SqlCommand cmd = new SqlCommand(sql1,cn))
{
cmd.Parameters.AddWithValue("#fileName", myfilename);
cn.Open();
FileId= (int)cmd.ExecuteScalar();
}
}

Related

how to use for loop to read data from mysql table

I have mysql Database and i want to read data from there in my web application with for loop instead of foreach loop.
MySqlConnection conn = new MySqlConnection(connStr);
conn.Open();
string query = "SELECT * FROM survey ORDER BY datetime DESC";
MySqlCommand com = new MySqlCommand(query, conn);
com.CommandTimeout = 0;
MySqlDataAdapter da = new MySqlDataAdapter(com);
DataTable ds = new DataTable();
da.Fill(ds);
conn.Close();
foreach (DataRow item in ds.Rows)
{
string unique = item.ItemArray[4].ToString();
var sur = db2.VoipSurveys.Where(a => a.UniqueId == unique).SingleOrDefault();
if (sur == null)
{
VoipSurvey vs = new VoipSurvey()
{
Date = Convert.ToDateTime(item.ItemArray[1]),
Point = Convert.ToInt32(item.ItemArray[2]),
CallerId = item.ItemArray[3].ToString(),
UniqueId = item.ItemArray[4].ToString(),
AgentNumber = item.ItemArray[5].ToString(),
AgentName = item.ItemArray[6].ToString(),
QueueNumber = item.ItemArray[7].ToString()
};
db2.VoipSurveys.Add(vs);
db2.SaveChanges();
}
}
I need reading data from specific index like reading data in mysql table from this Date until now. and i think my problem would be solved with for loop
You can use a DataView RowFilter also:
// Create a DataView
DataView dv = new DataView(dt);
dv.RowFilter = " (Date >= #" +
Dateyouwanttouse +
"# And Date <= #" +
DateTime.Now +
"# ) ";
Simply do this:
foreach (DataRowView rowView in dv)
{
DataRow row = rowView.Row;
// Do something //
}

Reader mysql keeps returning null

MySqlCommand command = new MySqlCommand(selectCmd, myConnection);
command.CommandText = "SELECT idtolistsubsoorten FROM `vogelsoort` WHERE id= MAX (id)and vogelsoort.naam =#vogelsoortnam";
command.Parameters.Add("#vogelsoortnaam", MySqlDbType.VarChar).Value = vogel.Soortnaam;
reader = command.ExecuteReader();
reader.Read();
while (reader.Read())
{
string idpape = reader.;
subid = Convert.ToInt64(idpape);
}
the reader keeps returning an null value
Your SQL query has a mistake: There are two FROM commands:
SELECT idtolistsubsoorten
FROM `vogelsoort`
WHERE id= MAX (id)
FROM `vogelsoort`
and vogelsoort.naam = #vogelsoortnam
Try using this one instead:
SELECT idtolistsubsoorten
FROM `vogelsoort`
WHERE id= MAX (id)
and vogelsoort.naam = #vogelsoortnam
Also, you can try executing the query in your dbms before running it in PHP, this way you will have an error message with more verbose.
are you mistaking in query you should write single or double quotas when you use string
command.CommandText = "SELECT idtolistsubsoorten FROM `vogelsoort` WHERE id= MAX (id) and vogelsoort.naam =#vogelsoortnam";

not compiling the product expression in DataColumn showing error as "Cannot find column [max]."

While running the code it is giving error " Cannot find column [max]." but i have added the max and min column to the table in the dataset
MySql.Data.MySqlClient.MySqlConnection mycon = new MySqlConnection(GetConnectionString());
if (mycon.State != ConnectionState.Open)
{
string sqlCat = "SELECT * FROM out_of_mark_table";
string sqlProd = "SELECT * FROM scord_mark_table";
MySqlDataAdapter da = new MySqlDataAdapter(sqlCat, mycon);
DataSet ds = new DataSet();
try
{
mycon.Open();
da.Fill(ds, "out_of_mark_table");
da.SelectCommand.CommandText = sqlProd;
da.Fill(ds, "scord_mark_table");
}
finally
{
mycon.Close();
}
DataRelation relat = new DataRelation("CatProds", ds.Tables["out_of_mark_table"].Columns["test_id"], ds.Tables["scord_mark_table"].Columns["test_id"]);
ds.Relations.Add(relat);
DataColumn count = new DataColumn("Products (#)", typeof(int), "COUNT(Child(CatProds).test_id)");
DataColumn max = new DataColumn("Most Expensive Product", typeof(decimal), "MAX(Child(CatProds).total)");
DataColumn min = new DataColumn("Least Expensive Product", typeof(decimal), "MIN(Child(CatProds).total)");
DataColumn no=new DataColumn("No");
DataColumn IdCol = new DataColumn();
min.Caption = "min";
max.Caption = "max";
string expr = "max * min";
IdCol.ColumnName = "ID";
IdCol.DataType = Type.GetType("System.Int32");
IdCol.ReadOnly = true;
IdCol.AllowDBNull = false;
//IdCol.Unique = true;
IdCol.AutoIncrement = true;
IdCol.AutoIncrementSeed = 1;
IdCol.AutoIncrementStep = 1;
ds.Tables["out_of_mark_table"].Columns.Add(count);
ds.Tables["out_of_mark_table"].Columns.Add(max);
ds.Tables["out_of_mark_table"].Columns.Add(min);
ds.Tables["out_of_mark_table"].Columns.Add(IdCol);
DataColumn sum = new DataColumn("Sum of", typeof(int), expr, MappingType.Attribute);
**ds.Tables["out_of_mark_table"].Columns.Add(sum);**
IdCol.SetOrdinal(0);
GridView1.DataSource = ds.Tables["out_of_mark_table"];
GridView1.DataBind();
You have set the captions to "Max" and "Min", but the DataColumns's identifier is it's Ordinal or ColumnName. You have set the ColumnName via constructor to
"Most Expensive Product" and "Least Expensive Product"
So use
string expr = "[Most Expensive Product] * [Least Expensive Product]";
instead.

How to execute this SQL query using ADO.NET?

Given this EXACT ad-hoc query:
DECLARE #list AS TABLE (Name VARCHAR(20))
INSERT INTO #list(Name)
VALUES ('Otter', 'Lebron', 'Aaron', 'Brock')
SELECT *
FROM Users
WHERE FirstName in (SELECT Name from #list)
How can this be done using C# ADO.NET with a SqlParameter?
I'm using a modification of your orginal SQL for sample purposes.
DECLARE #list AS TABLE (Name VARCHAR(20));
INSERT INTO #list(Name)
VALUES ('PROCEDURE'),
('FUNCTION');
SELECT *
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE in (SELECT Name from #list)
You can use a Table-Valued Parameter
Here's a modified example taken from Table-Valued Parameters in SQL Server 2008 (ADO.NET)
using (SqlConnection cnn = new SqlConnection("Your connection string"))
{
var tableParam = new DataTable("names");
tableParam.Columns.Add("Name", typeof(string));
tableParam.Rows.Add(new object[] { "PROCEDURE" });
tableParam.Rows.Add(new object[] { "FUNCTION')" });
var sql = #"DECLARE #list AS TABLE (Name VARCHAR(20))
INSERT INTO #list(Name)
SELECT Name from #Names;
SELECT *
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE in (SELECT Name from #list)";
var sqlCmd = new SqlCommand(sql, cnn);
var tvpParam = sqlCmd.Parameters.AddWithValue("#Names", tableParam);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.Names";
cnn.Open();
using(SqlDataReader rdr = sqlCmd.ExecuteReader() )
{
while (rdr.Read())
Console.WriteLine(rdr["SPECIFIC_NAME"]);
}
}
But you need to define the type dbo.Names before it can work
Here's the type creation SQL
CREATE TYPE dbo.Names AS TABLE
( Name VARCHAR(Max));
Another option is to use an XML Parameter
using (SqlConnection cnn = new SqlConnection("Your connection string"))
{
var sql = #"DECLARE #list AS TABLE (Name VARCHAR(20))
INSERT INTO #list(Name)
SELECT t.name.value('.', 'varchar(MAX)')
FROM #Names.nodes('/Names/Name') as T(Name);
SELECT *
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE in (SELECT Name from #list)";
var sqlCmd = new SqlCommand(sql, cnn);
var s = new MemoryStream(ASCIIEncoding.Default.GetBytes("<Names><Name>PROCEDURE</Name><Name>FUNCTION</Name></Names>"));
var xmlParam = new SqlXml(s);
sqlCmd.Parameters.AddWithValue("#Names", xmlParam);
cnn.Open();
using(SqlDataReader rdr = sqlCmd.ExecuteReader() )
{
while (rdr.Read())
Console.WriteLine(rdr["SPECIFIC_NAME"]);
}
}

Problem access insertion syntax

I don't get it!
I'm doing a simple insert in an access db.
static void EcrireDansBD()
{
//Connection a la BD
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=me.mdb";
OleDbConnection conn = new OleDbConnection(connectionString);
//works
string sql = "INSERT INTO HQ_POINTS (NORD,EST,ELEV) VALUES (1,2,3)";
//Syntax error in INSERT INTO statement
string sql = "INSERT INTO HQ_POINTS (NORD,EST,ELEV,DESC) VALUES (1,2,3,'ok')";
//Syntax error in INSERT INTO statement
string sql = "INSERT INTO HQ_POINTS (NORD,EST,ELEV,DESC) VALUES (1,2,3,ok)";
//Syntax error in INSERT INTO statement
string sql = "INSERT INTO HQ_POINTS (NORD,EST,ELEV,DESC) VALUES (1,2,3,\"ok\")";
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
Here is the table:
alt text http://img1.imagilive.com/0810/Capturee43.PNG
Help?
DESC is a reserved keyword which is used for ordering (ORDER BY column ASC/DESC).
you have to quote it: use [DESC] instead