Dodawanie rekordów do bazy SQL server

0

Witam, piszę prostą aplikację do obsługi bazy danych. Mam problem z dodwaniem rekorów do tabeli. Połączenie z tabela dziala, wyswietla rekordy, natomiast nie dziala dodwanie , aplikacja zawiesza sie a VS poświetla ten wiersz

 da.InsertCommand.ExecuteNonQuery();  

cały kod wygląda tak:

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.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;

namespace WindowsFormsApplication5
{
    public partial class Form2 : Form
    {
        SqlConnection cs = new SqlConnection(@"Data Source= KAMIL\SQLEXPRESS; Initial Catalog=Projekt_Kamil; Integrated Security=TRUE");
        SqlDataAdapter da = new SqlDataAdapter();
        DataSet ds = new DataSet();

        public Form2()
        {
            InitializeComponent();
        }

        
        private void button2_Click(object sender, EventArgs e)
        {
            da.SelectCommand = new SqlCommand("Select * from Klient", cs);
            da.Fill(ds);

            dg.DataSource = ds.Tables[0];

        }

        private void button1_Click(object sender, EventArgs e)
        {
           
            da.InsertCommand = new SqlCommand("INSERT INTO Klient VALUES (@imie,@nazwisko,@adres,@telefon,@data_urodzenia");
            da.InsertCommand.Parameters.Add("@imie", SqlDbType.VarChar).Value = txtImie.Text;
            da.InsertCommand.Parameters.Add("@nazwisko", SqlDbType.VarChar).Value = txtNazwisko.Text;
            da.InsertCommand.Parameters.Add("@adres", SqlDbType.VarChar).Value = txtAdres.Text;
            da.InsertCommand.Parameters.Add("@telefon", SqlDbType.Int).Value = txtTelefon.Text;
            da.InsertCommand.Parameters.Add("@data_urodzenia", SqlDbType.Date).Value = txtData.Text;

            cs.Open();
            da.InsertCommand.ExecuteNonQuery();
            cs.Close();
        }
    }
}
 

Problem meczy mnie juz jakiś czas i nie mogę znaleźć rozwiazania.
Z góry dzięki za pomoc.

0

W zapytaniu masz KlientVALUES, rozdziel to spacją.

0

Niestety to nic nie pomogło, to nie w tym problem. Ten błąd zrobiłem teraz . Problem jest w tym, ze on nie może dodać do bazy, tak jakby nie miał praw do tego. Nie wiem czy dobrze myśle, to tylko moje obserwacje. Wyświetla wszystko ładnie, gorzej z dodaniem

0

Może dodaj try catch (Exception e) do da.InsertCommand.ExecuteNonQuery(); i zobacz czy coś zwróci ?

0

Dokładnie, albo jak wywali błąd, kliknij View Details i sprawdź co tam piszę. (w tym też co jest w InnerException).
@Mixer3394 Spróbuj też zmienić zapytanie na

INSERT INTO Klient (nazwaKolumny1,nazwaKolumny2,itd) VALUES (@imie,@nazwisko,@adres,@telefon,@data_urodzenia)

I jeszcze na nawiasu kończącego Ci brakuje.

0

Nic to nie daje, a błąd wywala taki:

Wyjątek System.InvalidOperationException nie został obsłużony
HResult=-2146233079
Message=ExecuteNonQuery: właściwość Connection nie została zainicjowana.
Source=System.Data
StackTrace:
w System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
w System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
w System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
w WindowsFormsApplication5.Form2.button1_Click(Object sender, EventArgs e) w c:\Users\Kamil\Documents\Visual Studio 2013\Projects\WindowsFormsApplication5\WindowsFormsApplication5\Form2.cs:wiersz 68
w System.Windows.Forms.Control.OnClick(EventArgs e)
w System.Windows.Forms.Button.OnClick(EventArgs e)
w System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
w System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
w System.Windows.Forms.Control.WndProc(Message& m)
w System.Windows.Forms.ButtonBase.WndProc(Message& m)
w System.Windows.Forms.Button.WndProc(Message& m)
w System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
w System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
w System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
w System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
w System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
w System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
w System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
w System.Windows.Forms.Application.Run(Form mainForm)
w WindowsFormsApplication5.Program.Main() w c:\Users\Kamil\Documents\Visual Studio 2013\Projects\WindowsFormsApplication5\WindowsFormsApplication5\Program.cs:wiersz 19
w System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
w System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
w Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
w System.Threading.ThreadHelper.ThreadStart_Context(Object state)
w System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
w System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
w System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
w System.Threading.ThreadHelper.ThreadStart()
InnerException:

0

Nie ustawiłeś właściwości Connection

da.InsertCommand.Connection = cs;

http://stackoverflow.com/questions/10263094/executenonquery-connection-property-has-not-been-initialized

0
 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.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;

namespace WindowsFormsApplication5
{
    public partial class Form2 : Form
    {
        SqlConnection cs = new SqlConnection(@"Data Source=KAMIL\SQLEXPRESS;Initial Catalog=Projekt_Kamil;Integrated Security=True");
        SqlDataAdapter da = new SqlDataAdapter();
        DataSet ds = new DataSet();

        public Form2()
        {
            InitializeComponent();
        }

        
        private void button2_Click(object sender, EventArgs e)
        {
            da.SelectCommand = new SqlCommand("Select * from Klient", cs);
            da.Fill(ds);

            dg.DataSource = ds.Tables[0];

        }

        private void button1_Click(object sender, EventArgs e)
        {
            
            da.InsertCommand = new SqlCommand("INSERT INTO Klient (imie, nazwisko, adres, telefon, data_urodzenia) VALUES (@imie , @nazwisko , @adres , @telefon , @data_urodzenia)");
            da.InsertCommand.Connection = cs;
            da.InsertCommand.Parameters.Add("@imie", SqlDbType.VarChar).Value = txtImie.Text;
            da.InsertCommand.Parameters.Add("@nazwisko", SqlDbType.VarChar).Value = txtNazwisko.Text;
            da.InsertCommand.Parameters.Add("@adres", SqlDbType.VarChar).Value = txtAdres.Text;
            da.InsertCommand.Parameters.Add("@telefon", SqlDbType.Int).Value = txtTelefon.Text;
            da.InsertCommand.Parameters.Add("@data_urodzenia", SqlDbType.VarChar).Value = txtData.Text;

            
            cs.Open();
            
            da.InsertCommand.ExecuteNonQuery();
            
           
            cs.Close();
            MessageBox.Show("Pomyślnie dodano klienta");
        }
    }
}

Jednak dalej jest ten sam błąd...

0

Może coś jest z ta baza danych, gdy chce połączyć ja za pomocą ekspoloratora serwisu wyskakuje taki błąd.
78d6638be6.png

0

Przesyłam link do mojego projektu http://1drv.ms/1EXAluW

0

Myślałem że to LocalDb jest, tak to nic nie zrobię.
Zainstaluj to co tu piszą: http://stackoverflow.com/questions/16906686/could-not-load-file-or-assembly-microsoft-sqlserver-management-sdk-sfc-version-1
btw powinieneś odinstalować polską lokalizację, bo takie coś tylko utrudnia odnalezienie rozwiązania problemu.

0

Stworzyłem nowa baze danych, i działa to dodaje po woli columny, chce zobaczyc, która powoduje problem. Chyba, że coś z tamtą baza danych jest nie tak.

0

Wiem gdzie jest błąd, chyba przekazuje źle date, mógłbyś rzucic okiem w sql jest

da.InsertCommand.Parameters.Add("@data_urodzenia", SqlDbType.Date).Value = txtData.Text; 

wpisuje np. 30.09.1993 a w sql jest taka tabela

data_urodzenia DATE NOT NULL,
1

Wprowadź datę w postaci mm.dd.rrrr

1 użytkowników online, w tym zalogowanych: 0, gości: 1