F
F
freshlemon2019-11-24 00:03:41
C++ / C#
freshlemon, 2019-11-24 00:03:41

How to pass double value to database?

Hello there is a local database created in MVS. You need to put a real value in it. I tried to make the data type float, decimal, numeric in the database, without .Replace(",", ".") for the field value does not want to write them to the database. And with .Replace(",", ".") rounds the number (or cuts off everything after "," , apparently). I tried Parameterized queries, it doesn't work (maybe I didn't try it correctly).
If we remove Replace, then com.ExecuteNonQuery(); throws the following error:
Unhandled exception of type 'System.Data.SqlClient.SqlException' in System.Data.dll
Additional information: Error converting data type nvarchar to float.

Exception details
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 tables in the database
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)
);

Collected the code in parts
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();

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Korotenko, 2019-11-24
@freshlemon

Cast types before insertion, and inserting directly from the interface is also not a very good idea.
Corrected the variables, you seem to have a form there. Look at my clearer and easier.

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();

T
tex0, 2019-11-24
@tex0

Read the exception text again.
There it is written in English and white that it was not possible to convert a string (nvarchar) to float. And now let's go to your code and see that you are really trying to write string values ​​from your TextBoxes into float fields (except for the tonn field, you have it in the database as a string, everything should be fine with it). You need to convert these string values ​​to double. For example apply double.Parse(string).
Well, then you have to "squat" with separators =) Good luck!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question