How to get USERID from accessdatabase - sql

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.

Related

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

c# - SqlReader of Read() not working

Problem: SqlReader of Read() not working
User Action:
enter their ID in a textbox and click a button
Program Action:
Select their name from database by given ID value
Then Print their name with HI! Message in RichTextBox or in Textbox
Error List:
No Error
Database:
Schema - dbo
Name - Sheet#Attendance
Here is my code:
private void swipe_button_Click(object sender, EventArgs e)
{
String ID_givenbyUSER = IDtxtBox.Text;
SqlConnection sqlConn = null;
sqlConn = new SqlConnection("Data Source=HOME-PC\\SQLEXPRESS;Initial Catalog=ABC_SchoolDB;Integrated Security=True");
sqlConn.Open();
SqlCommand cmd = new SqlCommand("select Student_Name from dbo.Sheet#Attendance where Serial_Id=" + " ' " + ID_givenbyUSER + " ' ", sqlConn);
SqlDataReader sqlReader = cmd.ExecuteReader();
richTxtBox.Clear();
richTxtBox.AppendText("Hi buddy "); //This line works
while (sqlReader.Read())
{
richTxtBox.AppendText("Hi buddy "); //But,Its not work
pwdbox.Text = (sqlReader["Student_Name"].ToString()); //Its not work too
}
if (sqlConn != null)
{
sqlConn.Close();
sqlConn = null;
}
}
}
I think your problem is here:
SqlCommand cmd = new SqlCommand("select Student_Name from dbo.Sheet#Attendance where Serial_Id=" + " ' " + ID_givenbyUSER + " ' ", sqlConn);
try this instead:
SqlCommand cmd = new SqlCommand("select Student_Name from dbo.Sheet#Attendance where Serial_Id='" + ID_givenbyUSER + "'", sqlConn);
Notice the part where you concatenate the single-quotes? It had spaces around them so your query would look like:
Where Serial_Id= ' Name '
The space in front of the user supplied value was probably causing your query to not return any rows.

Select SCOPE_IDENTITY not executing after insert statement;

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;
}

"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 display rows based on search value which works for multiple columns

HI all,
I have an issue where i have to search rows in a datagrid view based on the key value given explicitly through textbox. This key value should be of any column in the datagridview.
But unforutunately it works only for one column (in the below code column used is b)
string ss;
ss = textBox1.Text;
SqlConnection con = new SqlConnection("data source=localhost;integrated security=true;initial catalog=da");
da = new SqlDataAdapter("select * from me where a='"+ss+"' ", con);
da.Fill(ds, "me");
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
DataView dv = ds.Tables[0].DefaultView;
//where b is a column in the table me. I need this function to work for multiple columns
dv.RowFilter = "b='" + ss + "'";
ds.Tables.Clear();
ds.Tables.Add(dv.ToTable());
ds.AcceptChanges();
da.Update(dt);
Datagrid View before selecting
ss = textBox1.Text;
SqlConnection con = new SqlConnection("data source=localhost;
integrated security=true;initial catalog=da");
da = new SqlDataAdapter("select * from me", con);
da.Fill(ds, "me");
DataView dv = ds.Tables[0].DefaultView;
dataGridView1.DataSource = dv;
dv.RowFilter = "col1='" + ss + "' and col2>=10";
EDIT:
Consider the following example,
DataTable dt = new DataTable();
DataView dv;
private void Form1_Load(object sender, EventArgs e)
{
dt.Columns.Add("No", typeof(int));
dt.Columns.Add("Name");
dt.Rows.Add(10, "abc");
dt.Rows.Add(11, "pqr");
dt.Rows.Add(12, "efg");
dv = dt.DefaultView;
dataGridView1.DataSource = dv;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
int no;
int.TryParse(textBox1.Text, out no);
dv.RowFilter = "No=" + no + " or Name like '%" + textBox1.Text + "%'";
}