Bor*_*tti 2 c# database executenonquery
我正在尝试将值添加到数据库中,但每次我尝试添加一些东西时,我都会收到错误ExecuteNonQuery()消息" 连接必须有效且打开. "而且我不知道该怎么办!!!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace ClientesClinica
{
public partial class frmCadastro : Form
{
MySqlConnection conect = new MySqlConnection("server = localhost; user id = root; database = clientes; password = '';");
public frmCadastro()
{
InitializeComponent();
}
private void frmCadastro_Load(object sender, EventArgs e)
{
}
private void btnCancela_Click(object sender, EventArgs e)
{
Close();
}
private void btnSalvar_Click(object sender, EventArgs e)
{
int cod;
string nome;
string end;
int tel;
cod = Convert.ToInt16(txtCodigo.Text);
nome = txtNome.Text;
end = txtEndereco.Text;
if (txtNome.Text == "")
{
MessageBox.Show("Favor digitar o nome");
}
if (txtCodigo.Text == "")
{
MessageBox.Show("Favor digitar o código");
}
conect.Close();
MySqlCommand insere = new MySqlCommand();
insere.CommandText = "INSERT INTO cliente(cod, nome, endereco) Values(@cod + ,'@nome', '@end');";
insere.Parameters.AddWithValue("@cod", cod);
insere.Parameters.AddWithValue("@nome", nome);
insere.Parameters.AddWithValue("@end", end);
conect.Open();
insere.ExecuteNonQuery();// THE ERROR IS HERE!!!!
conect.Close();
MessageBox.Show("Salvo");
}
Run Code Online (Sandbox Code Playgroud)
您需要打开连接并根据MSDN:SQLCommand将其提供给命令
string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection); //<- See here the connection is passes to the command
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
或者供您使用:
conect.Open(); //<- Open Connection first
MySqlCommand insere = new MySqlCommand();
insere.Connection = conect; //<- Set the Commands connection
insere.CommandText = "INSERT INTO cliente(cod, nome, endereco) Values(@cod + ,'@nome', '@end');";
insere.Parameters.AddWithValue("@cod", cod);
insere.Parameters.AddWithValue("@nome", nome);
insere.Parameters.AddWithValue("@end", end);
insere.ExecuteNonQuery();
conect.Close();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14421 次 |
| 最近记录: |