Can someone tell me how to fix this error?
SqlCommand cmd = new SqlCommand(sqlCmd, conn)
--> conn: Aurgument type 'System.Data.OleDb.OleDbConnection' is not assignable to parameter type 'System.Data.SqlClient.SqlConnection'.
private void Form1_Load(object sender, EventArgs e)
{
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=C:\\Users\\KevinDW\\Desktop\\dotNET\\Week 5\\Prak1\\demo1.accdb";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
string sqlCmd = "SELECT CursusNaam FROM tblCursus";
SqlCommand cmd = new SqlCommand(sqlCmd, conn);
using (SqlDataReader reader = cmd.ExecuteReader())
{
listBox1.Items.Add(reader);
}
conn.Close();
}
}
You're mixing up Sql and OleDb
Use OleDbCommand instead of SqlCommand
and use OleDBDataReader instead of SqlDataReader
For example:
private void Form1_Load(object sender, EventArgs e)
{
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=C:\\Users\\KevinDW\\Desktop\\dotNET\\Week 5\\Prak1\\demo1.accdb";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
string sqlCmd = "SELECT CursusNaam FROM tblCursus";
OleDbCommand cmd = new OleDbCommand(sqlCmd, conn);
using (OleDBDataReader reader = cmd.ExecuteReader())
{
listBox1.Items.Add(reader);
}
conn.Close();
}
}
You are using SqlCommand/etc which requires the use of SqlConnection object instead of OleDbConnection.
Is it a SQL database you are connecting to? If so use SqlConnection instead
Edit: Obviously not, reading the connection string ... :D
Related
This is the code I'm working with right now, I don't get any errors so I can't pinpoint where it's not working:
private void btnAdd_Click(object sender, EventArgs e)
{
string constring = $"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=" +
Directory.GetCurrentDirectory().ToString() + "\\BarcodeDB.mdf;Integrated Security=True";
string query =
"INSERT INTO Products (Barcodes, Name, EDate, Quantity, Price) VALUES (#barcodeValue, #nameValue, #dateValue, #quantityValue, #priceValue) ;";
SqlConnection conDataBase = new SqlConnection(constring);
conDataBase.Open();
using (var cmd = new SqlCommand(query, conDataBase))
{
cmd.Parameters.AddWithValue("#barcodeValue", tbxBar.Text);
cmd.Parameters.AddWithValue("#nameValue", tbxName.Text);
cmd.Parameters.AddWithValue("#dateValue", dateDate.Value.Date);
cmd.Parameters.AddWithValue("#quantityeValue", tbxQua.Text);
cmd.Parameters.AddWithValue("#priceValue", tbxPrice.Text);
}
conDataBase.Close();
}
The code might just be wrongly build or I could be missing some part I'm not sure.
I figured out what was not working, was the connection string. So opening a new question for that.
What i had to do is to open the connection and then execute the command
You're not actually running the command. You need to call ExecuteNonQuery or ExecuteScalar:
using (var cmd = new SqlCommand(query, conDataBase))
{
// set parameters...
cmd.ExecuteNonQuery();
}
Can someone help me out?
I just get as result tb_localidade: System.Data.SqlClient.SqlDataReader
Why? Here is the code:
private void btn_normalizar_Click(object sender, EventArgs e)
{
//connection string - one or other doenst work
//SqlConnection conn = new SqlConnection("DataSource=FRANCISCO_GP;Initial Catalog=Normalizacao;Integrated Security=True;");
SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString);
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader leitor = cmd.ExecuteReader();
tb_localidade.Text = leitor.ToString();
conn.Close();
}
You can do this by calling Read() on your data reader and assigning the results:
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlDataReader leitor = cmd.ExecuteReader();
while (leitor.Read())
{
tb_localidade.Text = leitor["ART_DESIG"].ToString();
}
}
}
}
Another note is that using a using block for your SqlConnection and SqlCommand objects is a good habit to get into.
Note: this is assigning the result to the tb_localidade.Text for every row in the resultset. If you are only intending for this to be one record, you might want to look into .ExecuteScalar() instead (see below).
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
tb_localidade.Text = cmd.ExecuteScalar().ToString();
}
}
}
before execute "executeReader()" then you must read to get results.
Improvement on Siyual's response. You're only looking for a single result, and this explicitly disposes both the connection and the datareader.
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using(SqlCommand cmd = new SqlCommand(sql, conn)) {
using(SqlDataReader leitor = cmd.ExecuteReader())
{
if (leitor.Read())
{
tb_localidade.Text = leitor["ART_DESIG"].ToString();
}
}
}
}
}
you should just this
SqlDataReader leitor = cmd.ExecuteReader();
string res="";
while(leitor.Read())
{
res=leitor.GetValue(0).ToString()///////if in sql it is varchar or nvarshar
}
tb_localidade.Text = res;
actully datareader is a 1d table and we can access to this with GetValue or GetInt32 or ...
I have a app.config and a connection string that works perfectly.
App.config
<connectionStrings>
<add name="MyConnectionString"
connectionString="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=myDatabaseC;Data Source=agent_edx44-PC;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
My Form
private void btnSave_Click(object sender, RoutedEventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand("uspINSERT",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
.....some code
}
private void bindDataGrid()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand("uspSELECTALL",con);
cmd.Connection = con;
...some code
}
My problem is I want to put this line of code inside a subroutine so that I can call it in any methods.
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
Here is what i have done so far:
private void MyConnection()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
MyConnection()
con.Open();
SqlCommand cmd = new SqlCommand("uspINSERT",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
.....some code
}
But it has an error saying that:
The name 'con' does not exist in the current context
Here's how you should write those first two methods:
private void btnSave_Click(object sender, RoutedEventArgs e)
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
con.Open();
using (SqlCommand cmd = new SqlCommand("uspINSERT", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
//.....some code
}
}
}
private void bindDataGrid()
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
con.Open();
using (SqlCommand cmd = new SqlCommand("uspSELECTALL", con))
{
cmd.Connection = con;
//...some code
}
}
}
Now,to get your new code to work you need to return the connection from the MyConnection method:
private SqlConnection MyConnection()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
return con;
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
using (SqlConnection con = MyConnection())
{
con.Open();
using (SqlCommand cmd = new SqlCommand("uspINSERT", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
//.....some code
}
}
}
Now, I would go one step further and do this:
private void RunSqlCommand(string cmdText, Action<SqlConnection, SqlCommand> execute)
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
con.Open();
using (SqlCommand cmd = new SqlCommand(cmdText, con))
{
cmd.Connection = con;
execute(con, cmd);
}
}
}
Now your btnSave_Click method can become this:
private void btnSave_Click(object sender, RoutedEventArgs e)
{
RunSqlCommand("uspINSERT", (con, cmd) =>
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
//.....some code
});
}
Change your MyConnection method to this, it returns a SqlConnection:
private SqlConnection MyConnection()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
return con;
}
This is how to use:
using (var con = MyConnection())
{
//your code
}
using block will dispose your DB connection after you have done with it.
I am having a problem with the sql datareader. Whenever I try to read data it gives me an error saying invalid attemp to call Read when the reader is closed. Please help me figure out the problem
private void button1_Click(object sender, EventArgs e)
{
string name = this.textBox1.Text;
string connstring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Gardezi\Documents\Visual Studio 2012\Projects\homeWork2\homeWork2\Database1.mdf;Integrated Security=True";
SqlConnection con = new SqlConnection(connstring);
string query = "Select * from diaryDB";
SqlCommand com = new SqlCommand(query, con);
SqlParameter p = new SqlParameter("name", name);
con.Open();
SqlDataReader d = com.ExecuteReader();
con.Close();
deleteResult r = new deleteResult(d);
r.Show();
}
this is the constructor of deleteResult
public deleteResult(SqlDataReader d)
{
InitializeComponent();
while (d.Read())
{
this.comboBox1.Items.Add((d["Title"] +"-" +d["Description"]).ToString());
}
}
You can't read after closing the connection.
Just change this part of your code:
FROM
(...)
con.Close();
deleteResult r = new deleteResult(d);
(...)
TO
(...)
deleteResult r = new deleteResult(d);
con.Close();
(...)
Please try to use the using statement that correctly enclose the connection, the command and the reader in appropriate blocks.
private void button1_Click(object sender, EventArgs e)
{
string name = this.textBox1.Text;
string connstring = #"....";
string query = "Select * from diaryDB";
using(SqlConnection con = new SqlConnection(connstring))
using(SqlCommand com = new SqlCommand(query, con))
{
SqlParameter p = new SqlParameter("name", name);
con.Open();
using(SqlDataReader d = com.ExecuteReader())
{
deleteResult r = new deleteResult(d);
r.Show();
}
}
}
In this way the connection is kept open while you read from the reader. This is essential to avoid the error.
The more important point is that you don't have to worry to close and dispose the connection when it is no more needed. The exit from the using block close and dispose the connection, the command and the reader ALSO in case of exceptions.
I need to add a text box value to SQL Server database table. Below is my code:
private void button1_Click(object sender, EventArgs e)
{
string str = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\timetablesystem.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(str);
string qry = "insert into SubjectMaster (SubjectName) values (#TxtSubjectName)";
con.Open();
SqlCommand cmd = new SqlCommand(qry, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#TxtSubjectName", TxtSubjectName.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Added Successfully!!");
con.Close();
}
But, data should not add in table... please help me...
thanks for ur help...
Try debugging your query first if it works i think your connection with your db isnt working.
string str = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\timetablesystem.mdf;Integrated Security=True;User Instance=True";
is there supposed to be this '.' after data source Data Source=.\\SQLEXPRESS
try this and tell me what is the message information content
private void button1_Click(object sender, EventArgs e)
{
string str = "Server=.\SQLEXPRESS;Database=TestDB;Trusted_Connection=True;";
using( SqlConnection con = new SqlConnection(str)){
try{
con.Open();
string qry = "insert into SubjectMaster (SubjectName) values (#TxtSubjectName)";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#TxtSubjectName", TxtSubjectName.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Added Successfully!!");
}
catch{
MessageBox.Show("connection is failed!!");
}
}
}
try this
SqlConnection con = new SqlConnection(#"Data Source=SL-20\SQLEXPRESS;Initial Catalog=TestDB;User ID=sa;Password=sl123;");
string query = " insert into name(name)values('" + TextboxTest.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();