-2
私はC#の新機能ですが、私はmysqlデータベースを管理するための簡単なGUIを開発しています。 プログラムの最後まで接続を開いたままにする必要がありますが(接続を閉じると)、接続ボタンをクリックした後にデータが挿入されますが、プログラムは「接続が有効で開いている必要があります。私たちを手伝ってくれますか?接続は有効でオープンしている必要があります。C#
namespace MysqlConn
{
public partial class Form1 : Form
{
private static MySqlConnection conn;
MySqlCommand mcd;
private void button1_Click(object sender, EventArgs e)
{
GetConn();
}
public static MySqlConnection GetConn()
{
conn = new MySqlConnection("datasource=localhost;port=3306;username='+UserName'; password= '+PassWord'");
MessageBox.Show("OK..");
return conn;
}
public Form1()
{
InitializeComponent();
String DataBase = textBoxDb.Text;
String UserName = textBoxUserName.Text;
String PassWord = textBoxPassword.Text;
}
public void openCon()
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
}
public void closedConn()
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
public void executeQuery(String s)
{
try
{
mcd = new MySqlCommand(s, conn);
if (mcd.ExecuteNonQuery() == 1)
{
MessageBox.Show("Query executed");
}
else
{
MessageBox.Show("Query not executed");
}
} catch (Exception ex)
{
MessageBox.Show(ex.Message);
} finally
{
}
}
private void buttonInsert_Click_1(object sender, EventArgs e)
{
string s = "insert into prova_csharp.users (Name, Surname, Age) values ('"+textBoxName.Text+"', '"+textBoxSurname.Text+"', '"+textBoxAge.Text+"')";
executeQuery(s);
}
private void buttonUpdate_Click(object sender, EventArgs e)
{
string s = "update prova_csharp.users set Name='" + textBoxName.Text + "', Surname='" + textBoxSurname.Text + "', Age=" + textBoxAge.Text + " where Id=" + textBoxId.Text;
executeQuery(s);
}
private void buttonDelete_Click(object sender, EventArgs e)
{
string s = "delete from prova_csharp.users where Id = " + textBoxId.Text;
executeQuery(s);
textBoxId.Text = "";
}
}
}
あなたが接続を開いている唯一の場所は 'openCon()'の中にあり、決して呼び出されません。 – pay
エラーはかなり自明です。私はあなたが実際に 'openCon'を呼び出したり、そうでなければ' conn.Open'を呼び出すところがないので、接続が開いていないことをお勧めします。 –
また、パラメータ化されたクエリを使用してください。これらは、古典的なSQLインジェクションであり、そのようなインサートにユーザー入力(テキストボックス)を使用します。それを終えたら、そのコネクションにDisposeを呼び出します。 – Nikki9696