在数据输入之前,与数据库的连接关闭

本文关键字:数据库 连接 数据 输入 | 更新日期: 2023-09-27 17:51:07

我使用的是Visual Studio 2008, Microsoft Server Compact 3.5,脚本是为Windows Mobile 6.5.3 Professional编写的。

我有一个小的表单脚本连接到数据库文件,输入数据到表单后,当你选择按钮,数据应该更新或写入输入数据到数据库。

在脚本的某个地方,我在将数据放入数据库之前关闭了连接。

连接数据库显示连接成功!当我运行脚本生成器时,我没有得到任何错误。windows移动模拟器上的消息是:"ExecuteNonQuery需要一个打开的可用连接。连接的当前状态为关闭。"

如你所见,我是Visual Studio的新手。

下面是Form脚本:

using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlServerCe;
namespace testdbconnection
{
public partial class Form1 : Form
{
    public SqlCeConnection cn = new SqlCeConnection(@"Data Source = C:'Users'...'test.sdf");
    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        try
        {
            cn.Open();
        }
        catch (SqlCeException ex)
        {
            MessageBox.Show(ex.Message);
            Application.Exit();
        }
    }
    private void TextBoxes_TextChanged(object sender, EventArgs e)
    {
        if (textBox1.Text != "" && textBox2.Text != "")
        {
            button1.Enabled = true;
        }
        else
        {
            button1.Enabled = false;
        }
    }
    private void button1_Click(object sender, EventArgs e)
    {
        SqlCeCommand cm = new SqlCeCommand("INSERT INTO tblUsers(userName, age) VALUES (@userName, @age)", cn);
        cm.Parameters.AddWithValue("@userName", textBox1.Text);
        cm.Parameters.AddWithValue("@age", textBox2.Text);
        try
        {
            int affectedRows = cm.ExecuteNonQuery();
            if (affectedRows > 0)
            {
                MessageBox.Show("Insert success!");
                textBox1.Text = "";
                textBox2.Text = "";
            }
            else
            {
                MessageBox.Show("Insert failed!");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

}

在数据输入之前,与数据库的连接关闭

 private void button1_Click(object sender, EventArgs e)
    {
using (cn)
{
        SqlCeCommand cm = new SqlCeCommand("INSERT INTO tblUsers(userName, age) VALUES (@userName, @age)", cn);
        cm.Parameters.AddWithValue("@userName", textBox1.Text);
        cm.Parameters.AddWithValue("@age", textBox2.Text);
        try
        {
cn.open();
            int affectedRows = cm.ExecuteNonQuery();
            if (affectedRows > 0)
            {
                MessageBox.Show("Insert success!");
                textBox1.Text = "";
                textBox2.Text = "";
            }
            else
            {
                MessageBox.Show("Insert failed!");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}