@freshlemon

Как передать значение типа double в базу данных?

Здравствуйте, есть локальная база данных, созданная в MVS. В нее нужно поместить вещественное значение. Пробовал в БД делать тип данных float, decimal, numeric, без .Replace(",", ".") для значения поля не хочет записывать их в БД. А с .Replace(",", ".") округляет число (или отсекает всё что после "," , видимо). Пробовал Параметризованные запросы, не выходит (может не правильно пробовал).

Если убираем Replace, то com.ExecuteNonQuery(); выдает следующую ошибку:
Необработанное исключение типа "System.Data.SqlClient.SqlException" в System.Data.dll
Дополнительные сведения: Error converting data type nvarchar to float.

Сведения исключения
System.Data.SqlClient.SqlException не обработано
Class=16
ErrorCode=-2146232060
HResult=-2146232060
LineNumber=1
Message=Error converting data type nvarchar to float.
Number=8114
Procedure=""
Server=(LocalDB)\MSSQLLocalDB
Source=.Net SqlClient Data Provider
State=5
StackTrace:
в System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
в System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
в System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
в System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
в System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
в System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
в System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
в Kurs_Mahlai.stoimost_FORM.addCena_B_Click(Object sender, EventArgs e) в C:\Users\Владислав\documents\visual studio 2015\Projects\Kurs_Mahlai\Kurs_Mahlai\Form6.cs:строка 70
в System.Windows.Forms.Control.OnClick(EventArgs e)
в System.Windows.Forms.Button.OnClick(EventArgs e)
в System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
в System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
в System.Windows.Forms.Control.WndProc(Message& m)
в System.Windows.Forms.ButtonBase.WndProc(Message& m)
в System.Windows.Forms.Button.WndProc(Message& m)
в System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
в System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
в System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
в System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
в System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
в System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
в System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
в System.Windows.Forms.Application.RunDialog(Form form)
в System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
в System.Windows.Forms.Form.ShowDialog()
в Kurs_Mahlai.Menu_FORM.ceni_B_Click(Object sender, EventArgs e) в C:\Users\Владислав\documents\visual studio 2015\Projects\Kurs_Mahlai\Kurs_Mahlai\Form1.cs:строка 47
в System.Windows.Forms.Control.OnClick(EventArgs e)
в System.Windows.Forms.Button.OnClick(EventArgs e)
в System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
в System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
в System.Windows.Forms.Control.WndProc(Message& m)
в System.Windows.Forms.ButtonBase.WndProc(Message& m)
в System.Windows.Forms.Button.WndProc(Message& m)
в System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
в System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
в System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
в System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
в System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
в System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
в System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
в System.Windows.Forms.Application.Run(Form mainForm)
в Kurs_Mahlai.Program.Main() в C:\Users\Владислав\documents\visual studio 2015\Projects\Kurs_Mahlai\Kurs_Mahlai\Program.cs:строка 19
в System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
в System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
в Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
в System.Threading.ThreadHelper.ThreadStart_Context(Object state)
в System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
в System.Threading.ThreadHelper.ThreadStart()
InnerException:


T-SQL таблицы в БД
CREATE TABLE [dbo].[t_stoimost] (
    [ID_stoimost] INT           IDENTITY (1, 1) NOT NULL,
    [mintonn]     FLOAT  NOT NULL,
    [maxtonn]     FLOAT  NOT NULL,
    [tonn]        NVARCHAR (50) NOT NULL,
    [cenakm]      FLOAT  NOT NULL,
    PRIMARY KEY CLUSTERED ([ID_stoimost] ASC)
);


Собрал код частями
SqlConnection con;
SqlCommand com;

public void Connection()
{
   string connect = @"Data Source=(LocalDB)\MSSQLLocalDB;
                               AttachDbFilename=|DataDirectory|\Database01.mdf;
                               Integrated Security=True";
   con = new SqlConnection(connect);
   con.Open();
}

Connection();
com = con.CreateCommand();
string tonn = addMin_TB.Text + " - " + addMax_TB.Text;
com.CommandText = "INSERT INTO dbo.t_stoimost (mintonn, maxtonn, tonn, cenakm) VALUES (N'" + addMin_TB.Text.ToString(CultureInfo.InvariantCulture).Replace(",", ".") + "',N'" + addMax_TB.Text.ToString(CultureInfo.InvariantCulture).Replace(",", ".") + "',N'" + tonn + "',N'" + addCena_TB.Text.ToString(CultureInfo.InvariantCulture).Replace(",", ".") + "')";
com.ExecuteNonQuery();
con.Close();
t_stoimostTableAdapter.Fill(database01DataSet.t_stoimost);
t_stoimostDataGridView.Update();
  • Вопрос задан
  • 1145 просмотров
Решения вопроса 1
firedragon
@firedragon
Не джун-мидл-сеньор, а трус-балбес-бывалый.
Приводите типы, до вставки, и вставлять напрямую из интерфейса тоже не очень идея.
Поправил переменные, у вас похоже форма там. Гляньте по моему понятней стало и проще.

com = con.CreateCommand();
            var addMin_TB_Text = "10,77777";
            var min = float.Parse(addMin_TB_Text);

            var addMax_TB_Text = "20,77777";
            var max = float.Parse(addMax_TB_Text);

            var addCena_TB_Text = "33,3";
            var cena = float.Parse(addCena_TB_Text);

            var tonn = addMin_TB_Text + " - " + addMax_TB_Text;

            com.CommandText = @"INSERT INTO t_stoimost (mintonn, maxtonn, tonn, cenakm) 
VALUES ( @mintonn, @maxtonn, @tonn, @cenakm )";
            
            com.Parameters.AddWithValue("@mintonn", min);
            com.Parameters.AddWithValue("@maxtonn", max);
            com.Parameters.AddWithValue("@tonn", tonn);
            com.Parameters.AddWithValue("@cenakm", cena);

            com.ExecuteNonQuery();
            con.Close();
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
@tex0
Ещё раз прочитайте текст исключения.
Там английским по белому написано что не удалось преобразовать строку (nvarchar) во float. А теперь идём в ваш код и видим что вы в поля типа float действительно пытаетесь записать строковые значения из своих TextBox(кроме поля tonn, оно у вас и в базе как строка, с ним всё должно быть нормально). Вам нужно сконвертировать эти строковые значения в double. Например применить double.Parse(string).
Ну а потом придётся "поприседать" с разделителями =) Удачи!
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы