I am trying to insert textbox value into database in my asp.net project. While using this code some errors are generating. Please help me.
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
con.ConnectionString = (#"connectionString");
con.Open();
cmd.Connection = con;
cmd.CommandText=("INSERT INTO tbl_Shading_Analysis(Load_Band) VALUES ('"+txtLoadBand.Text+"')");
cmd.ExecuteNonQuery();
con.Close();
}
I means the table tbl_Shading_Analysis doesn't exist in the connection you are using, it may cause if you have some triggers attached with the table there may be some issue.
Check if you are connected to the right server/database.
Check any triggers that run on that table as well and make sure all of them have the exact table name spelled correctly.
Try to use the full schema for the referenced table if you have checked above two point for correctness.
Ex: [DatabaseName].[Schema].[TableName] or [Database1].[smmdmm].[aid_data]
That error is coming because the table tbl_Shading_Analysis does not exist in your database.
Check your connection string if you have given the correct database name.
Check if you have created that table in the specified database.
Check if the spelling of the table name is different from what you have specified
Related
I want to insert values in "Navn" row and "Varenr" row in the DB table, when I'm clicking on a button. I have following code:
private void button2_Click(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True"))
{
try
{
SqlCommand cm = new SqlCommand();
cm.Connection = cn;
string col1 = textBox2.Text;
string col2 = textBox3.Text;
//generate sql statement
cm.CommandText = "INSERT INTO ProduktTable (Navn,Varenr) VALUES (#col1,#col2)";
//add some SqlParameters
SqlParameter sp_add_col1 = new SqlParameter();
sp_add_col1.ParameterName = "#col1";
//data type in sqlserver
sp_add_col1.SqlDbType = SqlDbType.NVarChar;
//if your data type is not number,this property must set
//sp_add_col1.Size = 20;
sp_add_col1.Value = textBox2.Text;
//add parameter into collections
cm.Parameters.Add(sp_add_col1);
//in your insert into statement, there are how many parameter, you must write the number of parameter
SqlParameter sp_add_col2 = new SqlParameter();
sp_add_col2.ParameterName = "#col2";
//data type in sqlserver
sp_add_col2.SqlDbType = SqlDbType.NVarChar;
//if your data type is not number,this property must set
//sp_add_col2.Size = 20;
sp_add_col2.Value = textBox2.Text;
//add parameter into collections
cm.Parameters.Add(sp_add_col2);
//open the DB to execute sql
cn.Open();
cm.ExecuteNonQuery();
cn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
But unfortunately, my data table is still empty:
I have set a breakpoint on the ExecuteNonQuery function, and it is triggered, when pressing on the button:
My table definition:
Your connection string is causing this:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True"
|DataDirectory| Your database that is being updated in this method is in your App Data Directory while the one you are trying to retrieve data from is in your project folder...
|DataDirectory| is a substitution string that indicates the path to the database. DataDirectory also makes it easy to share a project and also to deploy an application. For my PC my App Data Directory is:
C:\Users\MyUserName\AppData\...
If you browse to this location and then go to following folders
...\Local\Apps\2.0\Data
You will be able to find your particular application directory probably stored with your assembly name, or some hash when you go there you will find it the database there is being updated just fine. This connection string is best for deployment.
You can also try this:
If you notice that Server Explorer is detecting all the databases on my PC and you can notice that there are couple of MINDMUSCLE.MDF files but all are at different paths, this is because there is one file in DEBUG directory, one in my PROJECT directory, one in my APP DATA directory. The ones starting with the numbers are stored in my APP DATA directories... If you select your respective database file and then run the SELECT query against it, you will get your data.
I made a tutorial some time ago. May be it will help you:
Check the value that ExecuteNonQuery is returning. It should return an int with the number of records affected by the SQL statement.
If it comes back with a value other than 0, then you know a record is being inserted somewhere. Before you close the connection, run a SQL query against the table to select all of the records and see if they come back through the code.
SELECT * FROM ProduktTable
If you get some records, then you may want to double check the database you're looking at through the IDE and the one your inserting records into through the code. It could be possible that you've got two different databases and you're querying one while inserting into another one.
Those are the steps that I would go through to help narrow down the issue and sounds like something I've probably done before. I hope it helps!
I want to refresh the data automatically when change to the database is made.
I used this documentation:
And made the code on page load as:
protected void Page_Load(object sender, EventArgs e)
{
conString = "Data Source=MITEJ5-PC\\MITEJTECHONOLY;Initial Catalog=SSISTestDatabase;Integrated Security=SSPI;";
SqlDependency.Start(conString);
using (SqlConnection connection =
new SqlConnection(conString))
{
using (SqlCommand command =
new SqlCommand(GetSQL(), connection))
{
SqlCacheDependency dependency =
new SqlCacheDependency(command);
// Refresh the cache after the number of minutes
// listed below if a change does not occur.
// This value could be stored in a configuration file.
int numberOfMinutes = 1;
DateTime expires =
DateTime.Now.AddMinutes(numberOfMinutes);
Response.Cache.SetExpires(expires);
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetValidUntilExpires(true);
Response.AddCacheDependency(dependency);
connection.Open();
gv.DataSource = command.ExecuteReader();
gv.DataBind();
}
}
}
private string GetSQL()
{
return "select Name,Age,Address from tlbStudent;";
}
But when I run this , and made changes in SQL table data, it is not reflecting it on grid automatically.
Where can I be wrong in above code???
Please help me.
First you need to understand how SqlDependency works. Read The Mysterious Notification for a short introduction. Once you learn that the real feature at work is Query Notifications, you can learn about the restrictions in place for queries using notifications, see Creating a Query for Notification. Once such restriction is:
The projected columns in the SELECT statement must be explicitly stated, and table names must be qualified with two-part names. Notice that this means that all tables referenced in the statement must be in the same database.
For future problems read Troubleshooting Query Notifications.
The problem in
private string GetSQL()
{
return "select Name,Age,Address from tlbStudent;";
}
the table name should be 2 parts ""
private string GetSQL()
{
return "select Name,Age,Address from dbo.tlbStudent;";
}
according to the documentation
The projected columns in the SELECT statement must be explicitly stated, and table names must be qualified with two-part names. Notice that this means that all tables referenced in the statement must be in the same database.
I am working on a small application for personal use. It is about keeping some data readily available for me.
It just consists of a local database, functions to add, erase or modify 4 or 5 columns of data and displaying the table in a datagridview.
I have managed to add data to the table and I have managed to use a
SELECT * FROM mytable
statement to get the data and iterate through it but I want to bind the table to the datagridview.
Here is my current method of trying to bind the data:
private void button2_Click(object sender, EventArgs e)
{
string query = "SELECT * FROM myTable";
SqlCeConnection conn = new SqlCeConnection(conString);
using (SqlCeDataAdapter adap = new SqlCeDataAdapter(query, conn))
{
//the adapter will open and close the connection for you.
DataTable dat = new DataTable();
adap.Fill(dat);
dataGridView1.DataSource = dat;
}
}
When I run this code it does not throw an exception and if I change the name of the table to something that does not exists then it causes an exception telling that the table does not exists so I know that it is fetching my table. It simply is not showing it.
Any ideas?
Thanks
I'm trying to add records to a MS Access table 2007 using a C# application. My table consists of 3 fields: ID, Name and phone.
For example I tried to add a record for some one with these data: ID=1, Name=Boulis, and phone=1212422. The query didn't return any errors but I didn't find this data in my table.
But the most surprising matter is that when I tried to add the same previous data I got an error saying:
"The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again."
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\boulis.accdb;;Persist Security Info=False ";
con.ConnectionString = ConnStr;
con .Open();
MessageBox.Show("The connection is available now");
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "INSERT INTO info(ID, Name, phone) Values(#StudIDTxt, #StudNameTxt, #StudCNCITxt)";
cmd.Parameters.AddWithValue("#StudIDTxt",1);
cmd.Parameters.AddWithValue("#StudNameTxt", "boulis");
cmd.Parameters.AddWithValue("#StudCNCITxt", 1212422);
cmd.Connection = con;
cmd.ExecuteNonQuery();
MessageBox.Show("table is already updated");
}
The error message you receive on the second attempt clearly indicates that the first attempt was successful. If you already had the table open in Access before performing the INSERT in C# then you won't be able to see the new record until you either
close and re-open the table in Access, or
refresh the Datasheet View (or Form, or whatever). That can be accomplished by clicking the "Refresh All" button in the "Records" section of the "Home" tab (in Access 2010, anyway).
I have two functions. Insert functions provided by Soner Gönül (thanks),......
Table Name Students
Database
`Field Name Data Type
*StudentID Number
StudentName Text
StudentCNIC Text
StudentDOB Date/Time
*PK
using System.Data.OleDb;
private void Form1_Load(object sender, EventArgs e)
{
myCon = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Access_and_CSharp.accdb");
this.studentsTableAdapter.Fill(this.access_and_CSharpDataSet.Students);
}
Insert Function
private void Insertbtn_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Students(StudentID, StudentName, StudentCNIC, StudentDOB) Values(#StudIDTxt, #StudNameTxt, #StudCNCITxt, #StudDOBTxt)";
cmd.Parameters.AddWithValue("#StudIDTxt", StudIDTxt.Text);
cmd.Parameters.AddWithValue("#StudNameTxt", StudNameTxt.Text);
cmd.Parameters.AddWithValue("#StudCNCITxt", StudCNCITxt.Text);
cmd.Parameters.AddWithValue("#StudDOBTxt", StudDOBTxt.Text);
cmd.Connection=myCon;
myCon.Open();
cmd.ExecuteNonQuery();
myCon.Close();
}
And this is the update function
private void Updatebtn_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE [Students] set [StudentName] = ?, [StudentCNIC] = ?, [StudentDOB] = ? WHERE [StudentID] = ?";
cmd.Parameters.AddWithValue("#StudIDTxt", StudIDTxt.Text);
cmd.Parameters.AddWithValue("#StudNameTxt", StudNameTxt.Text);
cmd.Parameters.AddWithValue("#StudCNCITxt", StudCNCITxt.Text);
cmd.Parameters.AddWithValue("#StudDOBTxt", StudDOBTxt.Text);
cmd.Connection = myCon;
myCon.Open();
int rowsAffected = cmd.ExecuteNonQuery();
myCon.Close();
}
Problem 1 -
When I use the insert function I can see new data at the front end. But I cannot see the new data in Access. Other times when I close the application and restart, new recorded is not there. If I look in Access application and closed it then open VS2010 application new data is not there. What is going on?
Problem 2 -
When I use the update function, data remains updated while the application running first time. This is not true when the application is closed and running again. Where have I gone wrong?
For both of problems can anyone see where the problem(s) is/are?
Thanks in advance
EDIT
Updating to say I am looking the following website where I have gone wrong.
http://www.c-sharpcorner.com/uploadfile/e628d9/inserting-retrieving-records-from-ms-access-2007-using-odbc/
Update
I have Windows 7, MS Access 2007 and VS 2010. I am wondering if this is the problem. If it is then it's probably not worth the trouble. I have downloaded AccessDatabaseEngine but its 32bit so I don't know? Probably make my life easier if I use SQL Server instead of Access.
I think this question has been asked too many times.
For starters, make sure your database is NOT included with your project builds.
In Solution Explorer, find your database and specify Build Action = None and Copy to Output Directory = Do not copy
Your database should reside in a folder other than your bin folder, otherwise every time you fire up your project, you will copy to your output folder the same database that is in your project.
Instead, locate the database somewhere else (C:\Program Files (x86)\Common Files or some other location) and connect to it.
There could be other issues with your project, but this is a big one that is jumping out at me.