i want to insert data into sql server Compact edition the database table screenshot is Here >>>
i Want to add data in users the addition script is as follows
SqlCeConnection Con = new SqlCeConnection();
Con.ConnectionString = "Data Source = 'Database.sdf';" +
"Password='Password';";
Con.Open();
int Amount=Convert.ToInt32(AmBox.Text),
Code=Convert.ToInt32(MCode.Text),
Num=Convert.ToInt32(MNum.Text);
string Name=Convert.ToString(NBox.Text),
FName=Convert.ToString(SOBox.Text),
Address=Convert.ToString(AdBox.Text);
SqlCeCommand Query =new SqlCeCommand("INSERT INTO Users VALUES " +
"(++ID,Name,FName,Address,Code,Num,Amount)",Con);
Query.ExecuteReader();
When it runs it generates an error SAYING "The column name is not valid [Node Name (if any) =,Column name=ID ]
I don't figure out the problem kindly tell me thanks!
You should change your code to something like this
using(SqlCeConnection Con = new SqlCeConnection("Data Source = 'Database.sdf';" +
"Password='Password';")
{
Con.Open();
SqlCeCommand Query = new SqlCeCommand("INSERT INTO Users " +
"(Name,FName,Address,MCode,MNum,Amount) " +
"VALUES (#Name,#FName,#Address,#Code,#Num,#Amount)",Con);
Query.Parameters.AddWithValue("#Name", NBox.Text);
Query.Parameters.AddWithValue("#FName", SOBox.Text));
Query.Parameters.AddWithValue("#Address",AdBox.Text));
Query.Parameters.AddWithValue("#Code", Convert.ToInt32(MCode.Text));
Query.Parameters.AddWithValue("#Num", Convert.ToInt32(MNum.Text));
Query.Parameters.AddWithValue("#Amount" , Convert.ToInt32(AmBox.Text));
Query.ExecuteNonQuery();
}
The using statement guarantees the correct disposing of the
connection
The Parameter collection avoid Sql Injection Attacks and quoting
problems
Use of ExecuteNonQuery because this is an insert query.
Removed the ++ID, it is not a valid value to pass to the database
If the ID field is an Identity column, then you don't pass any value from code, but let the database calculate the next value.
Also, I'm not sure you really need the single quote in your connection string around the data source and password keys.
EDIT ---
Sometimes the .SDF database could be located in a different folder.
(Modern operating systems prevent writing in the application folder).
In this case is necessary to set the path to the SDF file in the connection string.
For example, the SDF could be located in a subfolder of the C:\ProgramData directory.
string conString = "Data Source=" +
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"MyAppData\\database.sdf") + ";Password=yourPassword;";
Related
I am trying to insert new data into an old .dbf database created with foxpro.
The database has a lot of columns and I dont need to fill every single one.
The connection itself works. But now im getting the exception "Field XY does not allow null values" for every single one I'm not adding in my insert statement. But the database is configured to allow null values.
I am using the following code:
OleDbConnection dbfcon = new OleDbConnection("Provider=VFPOLEDB.1;" +
"Data Source=" + Application.StartupPath + "\\Daten;");
dbfcon.Open();
String query = "INSERT INTO TB_KUVG (KDNR, Kuvg_id) " +
"VALUES(?,?)";
OleDbCommand cmd = new OleDbCommand(query, dbfcon);
cmd.Parameters.AddWithValue("#KDNR", 1);
cmd.Parameters.AddWithValue("#Kuvg_id", 1);
cmd.ExecuteNonQuery();
dbfcon.Close();
So what am I doing wrong?
Is it better to use another way to write into a .dbf from c#?
You are almost doing it right. Note that parameter names are not important and would be located positionally (ie: #KDNR is added first so that it correspond to first ? placeholder). What you are missing was, if the fields you don't pass doesn't accept NULL values then you should notify the connection that instead you want "empty" values for those fields ('' for string, / / for date, 0 for numeric and vice versa). To notify the driver, you execute 'SET NULL OFF' on the same connection.
While adding it, I revised your existing code a bit:
string dataFolder = Path.Combine(Application.StartupPath, "Daten");
String query = #"INSERT INTO TB_KUVG
(KDNR, Kuvg_id)
VALUES
(?,?)";
using (OleDbConnection dbfcon = new OleDbConnection("Provider=VFPOLEDB;Data Source=" + dataFolder))
{
OleDbCommand cmd = new OleDbCommand(query, dbfcon);
cmd.Parameters.AddWithValue("#KDNR", 1);
cmd.Parameters.AddWithValue("#Kuvg_id", 1);
dbfcon.Open();
new OleDbCommand("set null off",dbfcon).ExecuteNonQuery();
cmd.ExecuteNonQuery();
dbfcon.Close();
}
PS: Application.StartupPath might not be a good idea as it may be under "Program Files" which is read only.
PS2: It would be better if you added "VFP" tag there, instead of "DBF".
I have recently started a new job and they use Vistadb so I cannot change the software package before people suggest that. I have obtained out of the database a byte[] from a datatype of image that is used in there different systems so its data type cannot be changed from image to varbinary. I have made alterations to the byte[] and now need to put it back into the database in an new record however I cant seem to work out how the SQL Query should be for it so far I have.
zz is the byte[] the rest of it works fine just need a way to put that into my SQL Query
sql = "INSERT INTO TimeHistory(\"Data\",\"Name\",\"Units\",\"ParameterData\",\"StartTime\",\"EndTime\",\"StorageRate\",\"Measurement\") SELECT \'" +zz+ "\',\'" + Name + "\',\'" + Units + "\',\'" + ParameterData + "\',\'" + start + "\',\'" + end + "\',\'" + storage + "\'" + ",SELECT Max(ID)From Measurement;";
ExecuteScript(sql);
This is done with c#.net using WPF forms.
The key to doing what you want is to use parameters to pass data to your SQL operation, not to convert it to a string and embed it in the TSQL code. This is a best practice not just because it prevents needless type conversions (say from DateTime to string and string back to DateTime for storage) but also for security - it ensures the database engine only attempts to execute as code things you intended to be code, not data that happened to be escaped so it was evaluated as part of the string.
We have a good example of how to do this in our ADO.NET samples at:
Common Operations in ADO.NET
If you go down the page you'll see an example "Inserting Data Using a Parameterized Command" which will work with any type, like this:
using (VistaDBConnection connection = new VistaDBConnection())
{
connection.ConnectionString = #"Data Source=C:\mydatabase.vdb5";
connection.Open();
using (VistaDBCommand command = new VistaDBCommand())
{
int Age = 21;
command.Connection = connection;
command.CommandText = "INSERT INTO MyTable (MyColumn) VALUES (#age)";
command.Parameters.Add("#age", Age);
command.ExecuteNonQuery();
}
}
I have an WPF application that reads data from a file like so:
foreach (String line in File.ReadAllLines(file, Encoding.UTF8))
{}
Each line is then parsed and displayed on the screen which all works fine. Some of the data has cyrillic alphabet in it and the strings that I'm using to store this data in are also displayed fine on the screen in the app window.
However, after that I'm using those same strings to insert them into MySQL database. I'm building a query and firing it up MySqlCommand cmd = new MySqlCommand(query, conn); which successfully inserts a new line in the database with the appropriate information. Numbers are all fine, however all the strings that go into the database and have cyrillic letters are displayed as ????????
Database engine is InnoDB and the encoding of the table and all varchar fields in it is utf_general_ci so any idea what is going on and how can I save the correct string in the database?
EDIT:
Per request, here's some code. Database connection:
conn = new MySqlConnection();
conn.ConnectionString = "//censored//";
And the file reading / db loading, shortened for the purposes of this code snippet:
foreach (String line in File.ReadAllLines(file, Encoding.UTF8))
{
string[] tokens = line.Split('|');
string query = "INSERT INTO myTable SET first_name = '" + tokens[0] + "'" + ", last_name = '" + tokens[1] + "'";
MessageBox.Show(tokens[0]);
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.ExecuteNonQuery();
}
The message box shows the name as it should be but what goes into the database is ???????.
After some headbanging I did figure out where the problem is so posting an answer for all to see:
The key part is the way you establish your connection to the database:
conn.ConnectionString = #"Server = YOURSERVER; Database = YOURDB; Uid = YOURUSER ; Pwd = 'YOURPASSWORD'; charset=utf8;";
I was missing the charset=utf8; part before so I assume all kinds of non-utf8 junk was going to the database regardless of the fact that I was encoding in UTF8 on both sides of the connection. Hope this helps!
I have a SqlCommand that attempts to insert a row in a SQL Server database table. The column of interest is a nvarchar(100) and the data that needs to be input will include characters such as "-", ";" and "\". When I insert a string without these characters everything works fine. When I attempt to insert a string that includes these characters the code fails because these characters are literally understood by the code and thus reports a syntax error. I have resolved such an issue in TSQL alone using dynamic sql, however I cannot find any good references to perform this action in C#. I suppose I could create a stored procedure and pass the values, but is there a way in which I could efficiently perform this using C# alone? If so, How? Or is passing values to a Stored Procedure a better approach?
Here is a simplified version of the code:
String SQLServerInstanceNames = "ussqlclus-db43\ussqlclusdb43; ussqlclus-db44\ussqltrysdb44; ussqltrys-db45\ussqltrysdb45;"
//Create Connection (Get Connection string from Server Explorer)
SqlConnection myConnection = new SqlConnection("Data Source=SERVER1;Initial Catalog=Database1;Integrated Security=True");
//Open connection
try { myConnection.Open(); }
catch (Exception e) { Console.WriteLine(e.ToString()); }
SqlCommand myCommand = new SqlCommand("INSERT INTO [dbo].[Table1]" +
"([SQLServerInstanceNames])" +
"VALUES (SQLServerInstanceNames);", myConnection);
//Execute command
myCommand.ExecuteNonQuery();
//Close connection
try { myConnection.Close(); }
catch (Exception e) { Console.WriteLine(e.ToString()); }
Try with SqlParameters. It will save you from Sql Injection as well as from your current problem.
myCommand.Parameters.AddWithValue("#param1", myValueWithCharacters);
C# uses \ as a control character. You can ignore those by prepending the string with an # character:
String SQLServerInstanceNames = #"ussqlclus-db43\ussqlclusdb43; ussqlclus-db44\ussqltrysdb44; ussqltrys-db45\ussqltrysdb45;"
Just update your code like this to include parmeters in INSERT statement
SqlCommand myCommand = new SqlCommand("INSERT INTO [dbo].[Table1]" +
"([SQLServerInstanceNames])" + "VALUES (#SQLServerInstanceNames);", myConnection);
myCommand.Parameters.AddWithValue("#SQLServerInstanceNames", "instance name");
Notice I updated VALUES part and added #SQLServerInstanceNames – this is how you add parameters to your query.
Now that you use parameters you won’t have to worry about special characters. These will be handled automatically.
I am designing a database app, and have a form which populates with data from a sql database. If a user double clicks on any of the text boxes on the form they are able to change the value using an input box, which then executes the following code to update the database.
private void ProcessChanges(string strField, string strCurrentValue)
{
//...Connect To Database...//
string strCaseNo = txtCaseNo.Text;
string strConnect = BuildConnectionString();
SqlConnection linkToDB = new SqlConnection(strConnect);
linkToDB.Open();
//...Request User Input New Value...//
string strMessage = "Enter ammended details and click OK," + Environment.NewLine +
"or click Cancel to exit.";
string strInput = Interaction.InputBox(strMessage, "Case Details", strCurrentValue);
//...Send User Input to Database...//
string commandText = "UPDATE tblCases SET #FieldVal = #InputVal WHERE CaseNo = #CaseNoVal;";
SqlCommand sqlCom = new SqlCommand(commandText, linkToDB);
sqlCom.Parameters.Add("#FieldVal", SqlDbType.Text);
sqlCom.Parameters.Add("#InputVal", SqlDbType.Text);
sqlCom.Parameters.Add("#CaseNoVal", SqlDbType.VarChar);
sqlCom.Parameters["#FieldVal"].Value = strField;
sqlCom.Parameters["#InputVal"].Value = strInput;
sqlCom.Parameters["#CaseNoVal"].Value = strCaseNo;
int intQuery = sqlCom.ExecuteNonQuery();
MessageBox.Show(intQuery.ToString());
}
The problem is the database does not update at all. I know the connection is ok because the same ConnectionStringBuilder is used throughout my app. I have also added the messagebox at the end which tells me the return value of ExecuteNonQuery() which is '1', so that suggests a row has been updated. However nothing changes in my database and its really annoying me now.
You can't use variables for column names. You have to construct your sql string that the column names are embedded into the string.
string commandText =
"UPDATE tblCases SET [" + strField + "] = #InputVal WHERE CaseNo = #CaseNoVal;"
But you have to check the value of strField for sql injection attacks.
If you update the CommandText line as follows:
string commandText = "UPDATE tblCases SET #FieldVal = " + strField + " WHERE CaseNo = #CaseNoVal;";
and remove the lines
sqlCom.Parameters.Add("#FieldVal", SqlDbType.Text);
sqlCom.Parameters["#FieldVal"].Value = strField;
Be aware though that by doing this you are potentially opening yourself to sql injection attacks, so you need to really trust the values being supplied into this method or do some work to make sure that any value of strField does not contain actual SQL statements.
e.g. if strField contains ;[some malicious SQL here] then this will be run with the permissions of the user assigned to the connection.
#Jan has it. But as an aside you really should be disposing or closing your SqlConnection, from MSDN:
If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose. Close and Dispose are functionally equivalent. If the connection pooling value Pooling is set to true or yes, the underlying connection is returned back to the connection pool. On the other hand, if Pooling is set to false or no, the underlying connection to the server is actually closed.
The using construct is present in C# for just such a thing:
using (SqlConnection linkToDB = new SqlConnection(strConnect)
{
// use the linkToDb here
}