I'm unable to insert data into table. we are using local db. I'm not even getting any exception
string constr = ConfigurationManager.ConnectionStrings["server"].ConnectionString;
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("insert into Client_Name(Name) values('" + textBox1.Text + "')",con);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ee)
{
Console.Write("Exception");
}
}
In app.config
<connectionStrings>
<add name="server" connectionString="Data Source = (LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\msm.mdf;Integrated
Security=True;Connect Timeout=30" providerName="System.Data.SqlClient" />
</connectionStrings>
I have tried all the possible way, and got the best solution considering your scenario.
During an hour observation got to know due database connection
persistence issue you were having that problem try below snippet would
work as expected.
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\msm.mdf;Connect Timeout=30;Integrated Security=True;";
using (var _connection = new SqlConnection(connectionString))
{
_connection.Open();
using (SqlCommand command = new SqlCommand("Insert into [LocalTestTable] values (#name,#description)", _connection))
{
command.Parameters.AddWithValue("#name", "TestFlatName");
command.Parameters.AddWithValue("#description", "TestFlatDescription");
SqlDataReader sqlDataReader = command.ExecuteReader();
sqlDataReader.Close();
}
_connection.Close();
}
Hope that will resolve your problem without having anymore issue.
Related
Hello please help me out with this connection string and even my procedure properties are attached
try
{
conn = new SqlConnection("Server=RM-MOBL\MSSQLSERVER1;DataBase=master;Trusted_Connection=True;");
conn.Open();
SqlCommand cmd = new SqlCommand("dbo.new", conn);
cmd.CommandType = CommandType.StoredProcedure;
rdr = cmd.ExecuteReader();
Console.WriteLine(" connection success");
}
// I hope I have mentioned correct connection string but
// not able to execute my stored procedure
i am facing error
![please see error here ][3]
The above code might not be a best way to Connect the database.
In your web.config add these lines which will connect to your database inside <configuration> section
<connectionStrings >
<add name="myConnectionString" connectionString="Server=ServerName;Database=DatabaseName;User ID=UserId;Password=Password;Trusted_Connection=False;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
And in your C# file add these references
using System.Data.SqlClient;
using System.Web.Configuration;
Inside Public Class add this Connection
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
Now you can open the Connection by having con.Open();
Try this,if you are using local machine
SqlConnection con = new SqlConnection("Server=RANJITHM-OBL\MSSQLSERVER1;initial catalog=master;integrated security=true");
SqlCommand cmd = new SqlCommand("dbo.new", conn);
cmd.CommandType = CommandType.StoredProcedure;
if (con.State == ConnectionState.Closed)
con.Open();
rdr = cmd.ExecuteReader();
Console.WriteLine(" connection success");
I try to insert data into my database, all operations are done successfully but database does not update after the SQL query was executed. It is windows based application. I put the connection string in app.config file.
When I run this application code. and insert the data it show me the msg "Data inserted", but when I check the database there no data updated in database.... give me some solution.
I use Visual Studio 2013 and SQL Server 2012.
Here is my code:
namespace Sample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["cons"].ConnectionString.ToString());
sqlcon.Open();
string str = "insert into tab(name,pwd) values('" + textBox1.Text.ToString() + "','" + textBox2.Text.ToString() + "')";
SqlCommand cmd = new SqlCommand(str, sqlcon);
cmd.ExecuteNonQuery();
MessageBox.Show("Data inserted");
cmd.Clone();
}
catch(Exception E)
{
MessageBox.Show("No data inserted");
}
}
}
}
App.config
<configuration>
<connectionStrings>
<add name="cons"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename='|DataDirectory|\Database1.mdf';Integrated Security=True"/>
</connectionStrings>
</configuration>
hey i solve this problem myself
i just replace the full path in connection string with (|DataDirectory|\Database.mdf).... like this
<configuration>
<connectionStrings>
<add name="cons" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename='C:\Users\Dhaval\documents\visual studio 2013\Projects\Sample\Sample\Database.mdf';Integrated Security=True"/>
</connectionStrings>
</configuration>
so the connection string access right database of application.. not(.\bin\debug) "Database.mdf" file..
Firstly, to prevent injection attacks and to avoid syntax errors, use parameters. Secondly, to ensure resources are properly disposed of, use the "using" statements. Thirdly, show the error message thrown. The following (untested) code illustrates these techniques. Also, what is the cmd.Clone() used for?
private void button1_Click(object sender, EventArgs e)
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["cons"].ConnectionString.ToString());
try
{
using (sqlcon)
{
sqlcon.Open();
string str = "insert into tab(name,pwd) values(#Value1, #Value2)";
using (SqlCommand cmd = new SqlCommand(str, sqlcon))
{
cmd.Parameters.Add(new SqlParameter("Value1", TextBox1.Text));
cmd.Parameters.Add(new SqlParameter("Value2", TextBox2.Text));
cmd.ExecuteNonQuery();
MessageBox.Show("Data inserted");
//cmd.Clone();
}
}
}
catch (Exception E)
{
throw new Exception(E.Message);
}
finally
{
sqlcon.Close();
}
}
I am trying to upload a Microsoft Access Database into a Microsoft SQL Server Express Database.
The structure of the Access and the SQL Database are identical except for the name of the Primary Key.
Error Code:
System.InvalidOperationException: No data exists for the row/column. at System.Data.OleDb.OleDbDataReader.DoValueCheck(Int32 ordinal) at System.Data.OleDb.OleDbDataReader.GetValue(Int32 ordinal) at System.Data.OleDb.OleDbDataReader.get_Item(Int32 index) at ACCESStoMDF._Default.Button1_Click(Object sender, EventArgs e) in C:\Users\path2ACCESStoMDF\ACCESStoMDF\Default.aspx.cs:line 44
web.config
<configuration>
<connectionStrings>
<add name="ACCESSdb"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\path1\DBaccess.accdb;Persist Security Info=False;" />
<add name="MSSQLdb"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\MSSQLdb.mdf;User Instance=true;"
providerName="System.Data.SqlClient" />
</connectionStrings>
MSAccessTOMSSQL.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
String connStr = ConfigurationManager.ConnectionStrings["ACCESSdb"].ConnectionString;
String cmdStr = "SELECT * FROM [TableACCESS];";
try
{
using (OleDbConnection conn = new OleDbConnection(connStr))
{
using (OleDbCommand cmd = new OleDbCommand(cmdStr, conn))
{
conn.Open();
using (OleDbDataReader dr = cmd.ExecuteReader())
{
String connStr1 = ConfigurationManager.ConnectionStrings["MSSQLdb"].ConnectionString;
String cmdStr1 = "INSERT INTO [Table1] (col1,col2,col3) VALUES (#col1,#col2,#col3);";
try
{
using (SqlConnection conn1 = new SqlConnection(connStr1))
{
using (SqlCommand cmd1 = new SqlCommand(cmdStr1, conn1))
{
conn1.Open();
cmd1.Parameters.AddWithValue("#col1", dr[1]);
cmd1.Parameters.AddWithValue("#col2", dr[2]);
cmd1.Parameters.AddWithValue("#col3", dr[3]);
cmd1.ExecuteNonQuery();
conn1.Close();
cmd1.Dispose();
conn1.Dispose();
}
}
}
catch (Exception ex)
{
Label2.Text = "Insert Into: " + ex.ToString();
}
}
conn.Close();
cmd.Dispose();
conn.Dispose();
}
}
}
catch (Exception ex)
{
Label2.Text = "Access: " + ex.ToString();
}
}
An OleDbDataReader allows you to process the results of a SELECT query row-by-row. As shown in the documentation, you need to do something like
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0].ToString());
}
reader.Close();
Note also that the numeric index of the returned row is zero-based, so the first column is reader[0].
I am trying basic database insert and this code is waht I am running in visual studio 2010:-
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Visual Studio 2010\\WebSites\\WebSite3\\App_Data\\name.mdf;Integrated Security=True;User Instance=True";
SqlCommand cmd = new SqlCommand("insert into names values('" + TextBox1.Text + "')");
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
where am I wrong?
You created a connection and opened it, but you did not associate it with the SqlCommand. You can do this a couple of ways, either in the constructor of the SqlCommand or through the Connection property of the SqlCommand.
Additionally, you should use parameterized queries to prevent SQL Injection attacks. I'd also recommend putting the SqlConnection in a using block to ensure it is closed and properly disposed of. Putting all of that together gives you something like this:
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Visual Studio 2010\\WebSites\\WebSite3\\App_Data\\name.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("insert into names values(#name)", conn);
// Alternatively, you could do cmd.Connection = conn if you didn't pass
// the connection object into the SqlCommand constructor
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.ExecuteNonQuery();
}
}
You did not assign the connection to the command object. try:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Visual Studio 2010\\WebSites\\WebSite3\\App_Data\\name.mdf;Integrated Security=True;User Instance=True";
SqlCommand cmd = new SqlCommand("insert into names values('" + TextBox1.Text + "')");
cmd.Connection = conn; // <- this is the missing line
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
I have a SQL query and I want to execute it in C# on a button click, but when I click the
button the database is not being affected:
private void button1_Click(object sender, EventArgs e) {
String ConnectionString = "Data Source=localhost;Initial Catalog=mydb;Integrated Security=True";
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.CommandText = "INSERT INTO MedTab (MedID,MedName,Manf,MedProd,MedExp,TimeLeft,InStock) VALUES (4,'sdfs','sdfsd','sdfsdf','sdfsdf','sdfsd',33);";
con.Close();
}
The code you want is this:
String ConnectionString = "Data Source=localhost;Initial Catalog=mydb;Integrated Security=True";
String sql = "INSERT INTO MedTab (MedID,MedName,Manf,MedProd,MedExp,TimeLeft,InStock) VALUES (4,'sdfs','sdfsd','sdfsdf','sdfsdf','sdfsd',33);";
using (SqlConnection con = new SqlConnection(ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(sql, con))
cmd.ExecuteNonQuery();
}
Add cmd.ExecuteNonQuery after setting the command text.
You need to actually execute the query (try ExecuteNonQuery).
You're currently opening a connection, setting the statement to execute, then just closing the connection.