我正在尝试在我的数据库中插入值,但不幸的是,当我单击按钮时,我一次又一次地得到相同的错误,我已经在图片中显示了(请参见此处的图片:http://1.bp.blogspot.com/-oCH03jEnrdM/Uua4U9ddQZI/AAAAAAAABh0/BncJe0mHqQM/s1600/Capture.PNG)。错误是我的连接中的某个地方,我想是这样,但我是新手,因此我对这个错误不太了解请帮我整理:
这是我的代码:
public partial class Test : Form
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public Test()
{
InitializeComponent();
}
//Initialize values
private void Initialize()
{
server = "localhost";
database = "ADC";
uid = "**********";
password = "********";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//EndDatabase
//Creating Connection
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
case 1062:
MessageBox.Show("Duplicate Entry. Please try again with different cardentials");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
//End Connection
private void Test_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
var Pin = "1124";
var Sq= "What is your Name?";
var Sqa= "My Name is ";
var Bg= "B+";
var Int = "Programming";
var Skills= "Develepoment";
var webp = "xyz.com";
var addr= "DHA lahore";
var cnumber= "12324123";
string query = "INSERT INTO userprofilemoreinformation (Pin,SecurityQuestion,SecurityQuestionAnswer,BloodGroup,Interest,Skills,WebPage,Address,ContactNumber) VALUES(@Pin,@Sq,@Sqa,@Bg,@Int,@Skills,@webp,@addr,@cnumber)";
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("@Pin", Pin);
cmd.Parameters.AddWithValue("@Sq", Sq);
cmd.Parameters.AddWithValue("@Sqa", Sqa);
cmd.Parameters.AddWithValue("@Bg", Bg);
cmd.Parameters.AddWithValue("@Int", Int);
cmd.Parameters.AddWithValue("@Skills", Skills);
cmd.Parameters.AddWithValue("@webp", webp);
cmd.Parameters.AddWithValue("@addr", addr);
cmd.Parameters.AddWithValue("@cnumber", cnumber);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
}
答案 0 :(得分:0)
您似乎没有调用Initialize
方法。
public Test()
{
InitializeComponent();
Initialize();
}