【问题标题】:Why won't my data from textboxes from winform insert into local database2.mdf?为什么我来自 winform 的文本框中的数据不会插入到本地 database2.mdf 中?
【发布时间】:2018-03-31 23:18:56
【问题描述】:

我创建了用于打印条形码的小型应用程序,并编写了用于将数据插入我的 Database2.mdf 的代码。这是我的 app.config 连接字符串和我的数据库 2.mfg,其中包含表 Table(Model,Sasija,Trziste)。 app.config

这是我的代码:

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 System.Drawing.Imaging;
using System.Drawing.Printing;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;

namespace Barcode_ver1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        dateTimePicker1.Value = DateTime.Today;
    }


    private void textBox1_TextChanged(object sender, EventArgs e)
    {

        string barcode = textBox1.Text;


        Bitmap bitmap;
        if (textBox1.Text.Length == 0) {
            bitmap = new Bitmap(1, 100);
        } else
        {
            bitmap = new Bitmap(barcode.Length * 60, 110);
        }

        /*if (textBox1.Text.Length == 3)
        {
            textBox1.Text += "       ";
            textBox1.SelectionStart = textBox1.Text.Length;
        }*/
        using (Graphics graphics = Graphics.FromImage(bitmap))

        {
            Font oFont = new System.Drawing.Font("IDAutomationHC39M Free         Version", 12);
            PointF point = new PointF(2f, 2f);
            SolidBrush black = new SolidBrush(Color.Black);
            SolidBrush White = new SolidBrush(Color.White);
            graphics.FillRectangle(White, 0, 0, bitmap.Width,   bitmap.Height);
            graphics.DrawString("*" + barcode + "*", oFont, black, point);

        }
        using (MemoryStream ms = new MemoryStream())
        {
            bitmap.Save(ms, ImageFormat.Png);
            pictureBox1.Image = bitmap;
            pictureBox1.Height = bitmap.Height;
            pictureBox1.Width = bitmap.Width;
        }
        if (textBox1.Text.Length == 3)
            textBox3.Focus();
    }

    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        string barcode = textBox2.Text;

        Bitmap bitmap;
        if (textBox2.Text.Length == 0) {
            bitmap = new Bitmap(1, 100);
        } else {
            bitmap = new Bitmap(barcode.Length * 60, 110);
        }
        using (Graphics graphics = Graphics.FromImage(bitmap))

        {
            Font oFont = new System.Drawing.Font("IDAutomationHC39M Free Version", 12);
            PointF point = new PointF(2f, 2f);
            SolidBrush black = new SolidBrush(Color.Black);
            SolidBrush White = new SolidBrush(Color.White);
            graphics.FillRectangle(White, 0, 0, bitmap.Width, bitmap.Height);
            graphics.DrawString("*" + barcode + "*", oFont, black, point);

        }
        using (MemoryStream ms = new MemoryStream())
        {
            bitmap.Save(ms, ImageFormat.Png);
            pictureBox2.Image = bitmap;
            pictureBox2.Height = bitmap.Height;
            pictureBox2.Width = bitmap.Width;
        }
      }

    Bitmap bmp;

    private void btnPrint_Click(object sender, EventArgs e)
    {
        string connetionString = null;

        connetionString = @"Data Source=(LocalDB)\MSSQLLocalDB;     AttachDbFilename=C:\Users\NIKOPOL\Documents\Database2.mdf;Integrated Security=True; Connect Timeout=30";

        SqlConnection cnn = new SqlConnection(connetionString);

        try
        {
            SqlCommand cmd = new SqlCommand();
        cmd.Connection = cnn;

        cmd.CommandText = ("INSERT into Table VALUES (@Model,@Sasija,@Trziste)");

        cmd.Parameters.AddWithValue("@Model", textBox1.Text);
        cmd.Parameters.AddWithValue("@Sasija", textBox3.Text);
        cmd.Parameters.AddWithValue("@STrziste", textBox2.Text);


            cnn.Open();
            cmd.ExecuteNonQuery();
                        }

        catch (Exception ex)
        {
            MessageBox.Show("Nije moguce otvoriti konekciju");
        }
        finally
        {
            cnn.Close();
        }


        if (textBox1.Text.Length == 0 || textBox2.Text.Length == 0 || textBox3.Text.Length==0)
        {
            MessageBox.Show("Morate uneti polja", "Greška", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }
        if (printDialog1.ShowDialog() == DialogResult.OK) ;
        {
            printDocument1.Print();
        }
        textBox1.Clear();
        textBox3.Clear();
        textBox2.Clear();
        textBox1.Focus();
    }


    private void btnExit_Click(object sender, EventArgs e)
    {
        this.Close();
    }


    private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
    {
        //e.Graphics.DrawImage(bmp, 0, 0);
        e.Graphics.DrawImage(pictureBox1.Image, 170, 70, pictureBox1.Width, pictureBox1.Height);
        e.Graphics.DrawImage(pictureBox2.Image, 20, 185, pictureBox2.Width, pictureBox2.Height);
        Font oFont = new System.Drawing.Font("Arial", 12);
        e.Graphics.DrawString(label1.Text, oFont, Brushes.Black, 20, 75);            
        e.Graphics.DrawString(textBox1.Text, oFont, Brushes.Black, 20, 105);

        e.Graphics.DrawString(label3.Text, oFont, Brushes.Black, 80, 75);
        e.Graphics.DrawString(textBox3.Text, oFont, Brushes.Black, 80, 105);

        e.Graphics.DrawString(label2.Text, oFont, Brushes.Black, 20, 145);
        e.Graphics.DrawString(textBox2.Text, oFont, Brushes.Black, 20, 165);


        Font titleFont = new System.Drawing.Font("Arial", 20);
        e.Graphics.DrawString(label4.Text, titleFont, Brushes.Black, 76, 20);
    }

    private void textBox3_TextChanged(object sender, EventArgs e)
    {
        string barcode = textBox1.Text + textBox3.Text;


        Bitmap bitmap;
        if (textBox3.Text.Length == 0)
        {
            bitmap = new Bitmap(1, 100);
        }
        else
        {
            bitmap = new Bitmap(barcode.Length * 60, 110);
        }

        /*if (textBox1.Text.Length == 3)
        {
            textBox1.Text += "       ";
            textBox1.SelectionStart = textBox1.Text.Length;
        }*/
        using (Graphics graphics = Graphics.FromImage(bitmap))

        {
            Font oFont = new System.Drawing.Font("IDAutomationHC39M Free Version", 12);
            PointF point = new PointF(2f, 2f);
            SolidBrush black = new SolidBrush(Color.Black);
            SolidBrush White = new SolidBrush(Color.White);
            graphics.FillRectangle(White, 0, 0, bitmap.Width, bitmap.Height);
            graphics.DrawString("*" + barcode + "*", oFont, black, point);

        }
        using (MemoryStream ms = new MemoryStream())
        {
            bitmap.Save(ms, ImageFormat.Png);
            pictureBox1.Image = bitmap;
            pictureBox1.Height = bitmap.Height;
            pictureBox1.Width = bitmap.Width;
        }
        if (textBox3.Text.Length == 8)
            textBox2.Focus();
    }

    private void Form1_Shown(object sender, EventArgs e)
    {
        textBox1.Focus();
    }

它向我显示了来自 catch (Exception ex) 的消息“Nije moguce uspostaviti konekciju”。 有人能帮我吗? 我是编码和 c# 的新手,但我正在尽力而为。

【问题讨论】:

  • 请不要使用AddWithValue,而是使用Add并手动定义数据类型......并且,它会抛出任何异常吗?
  • Nije moguce uspostaviti konekciju 请把这个翻译成英文。
  • 不只是连接失败的消息(Nije moguce uspostaviti konekciju)
  • @Chetan Ranpariya 连接失败

标签: c# insert database-connection connection-string


【解决方案1】:

我认为你的 ConnectionString 是错误的。

  1. 转到服务器资源管理器:

  1. 右键>属性:

  1. 复制连接字符串:


  1. 示例:

使用 SqlConnection。

    SqlConnection con;
    con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=MyDataBase;Integrated Security=True");

插入示例

private void btnAdd_Click(object sender, EventArgs e)
    {
        con.Open();
        string Query = "insert into Professeur values ("+ txtID.Text +", '" + txtNom.Text + "', '" + txtPrenom.Text + "', '" + dtNaiss.Text + 
            "', '"+ txtEmail.Text +"', '"+ txtPass.Text +"', '" + dtAff.Text + "', '" + cbEtat.Text + "', "+ txtNum.Text +", " + cbLycee.Text + ")";
        cmd = new SqlCommand(Query, con);
        cmd.ExecuteNonQuery();
        con.Close();
    }

更新示例

private void btnEdit_Click(object sender, EventArgs e)
    {
        con.Open();
        string Query = "UPDATE Professeur SET nom = '" + txtNom.Text + "', prenom = '" + txtPrenom.Text +
            "', dateN = '" + dtNaiss.Text + "', email = '" + txtEmail.Text + "', pass = '"+ txtPass.Text +"' , dateAffLycee = '" + dtAff.Text +"' , nEfants = '" +txtNum.Text+
            "', idLycee = '" + cbLycee.Text + "' WHERE idProfesseur = " + txtID.Text;
        cmd = new SqlCommand(Query, con);
        cmd.ExecuteNonQuery();
        con.Close();
    }

删除示例

private void btnDelete_Click(object sender, EventArgs e)
    {
        con.Open();
        string Query = "DELETE FROM Professeur WHERE idProfesseur =" + txtID.Text;
        cmd = new SqlCommand(Query, con);
        cmd.ExecuteNonQuery();
        con.Close();
    }

从数据库到数据网格视图示例

con.Open();
string Query = "SELECT Professeur.idProfesseur, nom, prenom FROM Professeur, Demande WHERE idLycee = " + cbLycee.Text + " AND Demande.idProfesseur = Professeur.idProfesseur";
//SqlDataAdapter
da = new SqlDataAdapter(Query, con);
//Data Set
ds = new DataSet();
da.Fill(ds);
//DataGridView
dgv_Lycee.DataSource = ds.Tables[0];
con.Close();

【讨论】:

  • SQL Injection alert - 你应该永远将你的 SQL 语句连接在一起 - 使用 参数化查询 来避免 SQL注入 - 签出Little Bobby Tables
  • @Fatihi Youssef 我确实像你告诉我的那样,但现在它给了我一个例外
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-10
相关资源
最近更新 更多