Select SCOPE_IDENTITY not executing after insert statement; - sql

I try to get the id of the last inserted t ouristin the table as I put Selct SCOPE_IDENTITY; after the insert query.
The problem is that when I try to show the id of the inserted tourist in the label - just nothing happens. (only the insert query is executed);
string insertSQL = "INSERT INTO Tourist (Excursion_ID, Excursion_date_ID, Name_kir,Midname_kir, Lastname_kir)";
insertSQL += "VALUES (#Excursion_ID, #Excursion_date_ID, #Name_kir,#Midname_kir, #Lastname_kir);Select SCOPE_IDENTITY()";
string connectionString = "Data Source = localhost\\SQLExpress;Initial Catalog=excursion;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("#Excursion_ID", Convert.ToInt32(mynew2));
cmd.Parameters.AddWithValue("#Excursion_date_ID", Convert.ToInt32(mynewnewstring));
cmd.Parameters.AddWithValue("#Name_kir",tx888.Text);
cmd.Parameters.AddWithValue("#MidName_kir",tx888_1.Text);
cmd.Parameters.AddWithValue("#LastName_kir",tx888_2.Text);
int added = 0;
try
{
con.Open();
added = (int)cmd.ExecuteScalar();
if (added > 0)
{
lblproba.Text+=added.ToString();
}
}
catch (Exception ex)
{
//lblResult.Text = ex.Message;
}

Related

System.Data.SqlClient.SqlException: Incorrect syntax near "="

I try am trying to build a function that populates a table when given the name of the table and what parameter to order it by.
I think I am just making a syntax error in my SQL command but I can't find it. Please help.
public DataTable populateTable(string tableName, string orderByParameter)
{
DataTable table = new DataTable();
string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
string cmdString = "SELECT * FROM (value = #tbl) ORDER BY (parameter = #obp) DESC";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = cmdString;
cmd.Parameters.AddWithValue("#tbl", tableName);
cmd.Parameters.AddWithValue("#obp", orderByParameter);
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
try
{
GridView1.DataSource = table;
GridView1.DataBind();
return table;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
}
You can't have variables in table name or in 'order by' clause.
You could build the query dynamically as:
string cmdString = "SELECT * FROM [" + tableName + "] ORDER BY " + orderByParameter +" DESC";
With this you won't need to add the parameters #tbl and #obp to the command.
Note that this runs into SQL injection related vulnerabilities. So you shouldn't do this unless you are absolutely certain that the table with given name exists, and the orderByParameter is a valid expression.

SQL Count from specific Column in Database

I want to get a SQL Count of the number of records that pertain to my bundnum column and display it into my textblock. Any suggestions?
SqlConnection conn = new SqlConnection("db connection");
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "SELECT COUNT(*) FROM dbo.tablename WHERE bundnum = 'values' ";
conn.Open();
int returnValue = (int)comm.ExecuteScalar();
txtNumber.Text = returnValue.ToString();
Using Google, I found this helpful link and after some modification:
Int32 newCount = 0;
string newValue = "something";
string sql =
"SELECT COUNT(*) FROM dbo.tablename WHERE bundnum = '#myValue'";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#myValue", SqlDbType.VarChar);
cmd.Parameters["#myValue"].Value = newValue;
try
{
conn.Open();
newCount = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

Adding new data error

When i'm running this code, it says:
String or binary data would be truncated. The statement has been
terminated.
On the underlined area, can some one help me with this.
namespace ASP_05
{
public partial class AddEmployee : System.Web.UI.Page
{
public DataSet getDataset(string query)
{
String sConn = "Data Source=(local);Initial Catalog=medewerkers;Integrated Security=SSPI;";
SqlConnection conn = new SqlConnection(sConn);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(query, conn);
da.Fill(ds);
da.Dispose();
return ds;
}
protected void toevoegen_Click(object sender, EventArgs e)
{
String vn = voornaam.ToString();
String an = voornaam.ToString();
String a = voornaam.ToString();
String t = voornaam.ToString();
string query = "INSERT INTO tblMedewerkers (voornaam, achternaam, afdeling, toestelnummer) VALUES ('" + vn + "','" + an + "','" + a + "','" + t + "')";
this.execSQL(query);
}
public int execSQL(string query)
{
String sConn = "Data Source=(local);Initial Catalog=medewerkers;Integrated Security=SSPI;";
SqlConnection conn = new SqlConnection(sConn);
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
int i = cmd.ExecuteNonQuery();
conn.Close();
return i;
}
}
}
The data that you are inserting in the table for a particular column is more in size than what you have defined in the table. Hence you are getting this error. Go through your column definitions and also through the records you are inserting and check if any of the column have less size than data you are inserting

"Invalid object name" error in adapter.Fill method

I'm trying to make a DataSet from all tables of the AdventureWorks2012 database. But I'm getting an "Invalid object name " error in the adapter.Fill method.
Any ideas?
private void openDBButton_Click(object sender, RoutedEventArgs e)
{
DataSet myDataSet = new DataSet();
SqlDataAdapter myDataAdapter;
SqlCommand myCommand;
string conStr = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + dbPath.Text +
";Integrated Security=true";
SqlConnection connection = new SqlConnection(conStr);
connection.Open();
DataTable tables = connection.GetSchema("Tables");
foreach (DataRow table in tables.Rows)
{
if (table["TABLE_TYPE"].ToString() != "BASE TABLE")
continue;
string tableName = table["TABLE_NAME"].ToString();
string sqlCmd = "SELECT * FROM " + "[" + tableName + "]";
//SqlDataAdapter adapt = new SqlDataAdapter(new SqlCommand(sqlCmd, connection));
//adapt.FillSchema(myDataSet, SchemaType.Mapped, tableName);
myCommand = new SqlCommand(sqlCmd, connection);
myDataAdapter = new SqlDataAdapter(myCommand);
myDataAdapter.Fill(myDataSet, tableName); // here i'm get in trouble :)
}
}

How to get USERID from accessdatabase

I have a window in WPF. When I user enter name, I want to insert it to database and get USERID.
private void button1_Click(object sender, RoutedEventArgs e)
{
OleDbDataReader rd;
string name=comboBox1.Text;
OleDbConnection conn=new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|CellBiology.mdb;Persist Security Info=
True");
string sql = "select * from UserInformation where UserName='" + name+ "'";
conn.Open();
OleDbCommand cmd = new OleDbCommand(sql, conn);
rd = cmd.ExecuteReader();
if (rd.Read())
{
string id = rd["UserID"].ToString();
MessageBox.Show(id);
}
else
{
string sql2 = "insert into UserInformation(UserName) values ('" + ad+ "')";
OleDbCommand ne = new OleDbCommand(sql2, conn);
ne.ExecuteNonQuery();
**the problem is here.**
}
I believe you are never initializing the variable ad you are using in the following SQL:
string sql2 = "insert into UserInformation(UserName) values ('" + ad+ "')";
Which is a problem.