I've searched as much as I can and can't find anything to help me. So what I have is a script that reads/splits and stores data from a .txt file into some arrays. (The one listed here is Vndnbr). What I'm having trouble with is how to go about inputting each entry in the array as an entry under a column in a MS Access table? This is what I have so far:
public void AddToDatabase()
{
OleDbCommand command;
OleDbConnection connection =
new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=filepath");
foreach (string x in Vndnbr)
{
cmdstringVND[k] = "insert into Table1 (Vndnbr) Values (x)";
k++;
command = OleDbCommand(cmdstringVND[k],connection);
}
command.Parameters.AddWithValue("?", ReadFromFile("filepath"));
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
I'm not familiar with the Access library or what should be inserted in the first parameter of AddwithValue as I just copy pasted these lines after doing some research.
If someone could help me with how to add all the data from an array into a table it would be greatly appreciated, thanks.
There are many errors in your code
In your loop you don't use a parameter to store the value to be
inserted
You never creare the command. (Use new)
You try to execute only the last command because the ExecuteNonQuery is outside the loop
public void AddToDatabase()
{
string cmdText = "insert into Table1 (Vndnbr) Values (?)";
using(OleDbConnection connection = new OleDbConnection(.....))
using(OleDbCommand command = new OleDbCommand(cmdText, connection))
{
connection.Open();
command.Parameters.AddWithValue("#p1", "");
foreach (string x in Vndnbr)
{
command.Parameters["#p1"].Value = x;
command.ExecuteNonQuery();
}
}
}
I have changed you code to include the using statement to correctly close and dispose the connection and the command, then I have initialized the command outside the loop, passed a common string with as a parameter placeholder and initialized this parameter with a dummy value.
Inside the loop I have replaced the previous parameter value with the actual value obtained by your Vndnbr list and executed the command.
You'll want to change your SQL to this:
"insert into Table1 (Vndnbr) Values (#x)";
and then the AddWithValue is like this:
command.Parameters.AddWithValue("#x", ReadFromFile("filepath"));
All you're doing is saying, for this parameter name, I want this value assigned.
Related
I read lots of topics and tried many solutions, but it is not working for me, to insert my data to the database.
public static void Feltoltes(string szo_var, string szotagolva_var)
{
string query = "";
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
using (var command = new SqlCommand(query, conn))
{
command.Parameters.Clear();
command.CommandText = "INSERT INTO Szavak (Szo,Szotagolva) VALUES ('#szo','#szotagolva')";
command.Parameters.AddWithValue("#szo", szo_var);
command.Parameters.AddWithValue("#szotagolva", szotagolva_var);
System.Windows.Forms.MessageBox.Show(command.CommandText);
command.ExecuteNonQuery();
}
conn.Close();
}
}
This is my code. My connection string is the right one. If I insert to the database manually, than I can make SELECTs etc. Only the Insert is not working properly. It don't get any exception, looks like everything works, but nothing changes.
Every thing looks OK except for the insert command text.
Try the following:
command.CommandText = "INSERT INTO Szavak (Szo,Szotagolva) VALUES (#szo,#szotagolva)";
If you use single quates (') inside a SQL command text it will treat what is inside as a literal. And hence it cancels out your parameter designation #
I am trying to insert the text inside some text boxes into a database that I have in access. The code produces no errors but does not seem to add the items to the database.
The Database is called 'Database' the table is called 'TotalPlayerName' and the field is called 'Player Name'.
There are other fields in the table.
for(int i = 0; i < numberOfPlayers; i++){
using (OleDbConnection connection = new OleDbConnection(#"CONNECTION STRING"){
using (OleDbCommand command = new OleDbCommand(#"INSERT INTO TotalPlayerName ([Player Name]) VALUES(#p1)", connection)){
connection.Open();
command.Parameters.Add("#p1", OleDbType.VarWChar).Value = Convert.ToString(textBox[i].Text);
command.ExecuteNonQuery();
}
}
}
You might just need to declare #p1 because you call it in the INSERT statement, but it is never defined as a variable such as: varchar, int, ect, ect. This might work for what you are trying to do:
using (OleDbCommand command = new OleDbCommand(#"DECLARE #p1 VARCHAR(50) INSERT INTO TotalPlayerName ([Player Name]) VALUES(#p1)", connection)){
Also if at all possible i would definitely make it a stored procedure if you can. This works with SQL not sure if it will work with MS Access, but i would imagine so. The other thing you might want to do is make sure that it's finding the correct DB.
Database.dbo.TotalPlayerName
But that is probably not the issue, probably just the lack of variable declaration.
While I don't see what's specifically wrong with your code, I can tell you your methodology is off a bit. Specifically, for every iteration of your loop you are:
Establishing a connection to the database
Creating the insert command, creating a parameter and assigning the value
Executing the insert
It would be better all around if you did steps 1 and part of 2 once and then executed the statement within the loop like this:
using (OleDbConnection conn = new OleDbConnection(
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\foo.accdb"))
{
conn.Open();
OleDbCommand command = new OleDbCommand(
#"INSERT INTO TotalPlayerName ([Player Name]) VALUES (#p1)", conn);
command.Parameters.Add(new OleDbParameter("#p1", OleDbType.VarChar));
for (int i = 0; i < numberOfPlayers; i++)
{
command.Parameters[0].Value = textbox[i].Text;
try
{
command.ExecuteNonQuery();
}
catch (Exception ex)
{
// do something
}
}
conn.Close();
}
I assume textbox is an array or list of actual Text Box controls. If that's the case, then textbox[i].Text is already a string, and you shouldn't need to do anything special to make OLE recognize it as such.
On a final note -- add that try/catch and put a breakpoint there. Are you SURE it's not failing? If you are running in debug mode, there is no guarantee that your program will halt -- it may just return back to the form without reporting any error. It may not be until you attempt to deploy the app that you see the actual error occurring.
I have a database named testDB, which contains table Versions, which contains a column [Release Date] with datetime format.
Now, I want to read it in my C# Windows Service:
protected void SqlConnect()
{
SqlCommand comSql;
DateTime relDate;
SqlDataReader myReader = null;
using (SqlConnection myConnection = new SqlConnection(_server +
_username +
_password +
"Trusted_Connection=yes;" +
"database=testDB; " +
"connection timeout=30"))
{
try
{
myConnection.Open();
comSql = new SqlCommand("select [Release Date] from dbo.Version",
myConnection);
myReader = comSql.ExecuteReader();
while (myReader.Read())
{
//Here's my problem, explained below
}
}
catch
{
}
finally
{
if (myReader != null) myReader.Close();
}
}
}
Now, I want to assign the value stored in that column to relDate variable. However
relDate = myReader.GetDateTime();
requires GetDateTime to have column number passed there (if I understand this right). But I already selected column in my comSql. Is this the correct way to deal with this problem, ie. just putting the column number in the code?
EDIT: Ok judging by the answers I might word this question wrong or something.
I know that I must pass the column index to GetDateTime(). I ask if there's a way to do that without hardcoding it like GetDateTime(0).
You can use GetOrdinal method on the data reader to get ordinal of the column from its string name. In that way, you won't have to hardcode the column index.
GetOrdinal is also useful when you're reading data from the data reader in a loop. You can initialize the index variable before the loop starts and then use it in every iteration of the loop.
I have a combox called comboBox2 and i want to fill this combobox with a column named 'Stud_Name' of my database table called 'Student_Table'
I use the following code:
void Fillcombo()
{
string constring = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=C:\\ChaCha\\ChaCha\\chacha.mdf;Integrated Security=False";
string query = "select * from database.Student_Table";
SqlConnection condb = new SqlConnection(constring);
SqlCommand cmddb = new SqlCommand(query, condb);
SqlDataReader myreader;
try
{
condb.Open();
myreader = cmddb.ExecuteReader();
while(myreader.Read())
{
string sName = myreader.GetString("Stud_Name");
comboBox2.Items.Add(sName);
}
}
catch (Exception ex)
{
}
}
But, I am getting an error message like this:
The best overloaded method match for
'System.Data.Common.DbDataReader.GetString(int)' has some invalid
arguments.
How can I remove this error?
I use Visual Studio 2012.
Error message is clearly says;
There is no overload of SqlDataReader.GetString method that takes string as a parameter.
This method takes int as a parameter which is the number of zero-based column that you want to get.
You need to put as an integer value which is Stud_Name column number in your query.
For example; if your Stud_Name is the first column of your query, you can use it like;
string sName = myreader.GetString(0);
Also use using statement to dispose your SqlConnection, SqlCommand and SqlDataReader.
Your problem is the parameter you pass to the method called GetString. Uou should pass there the index of the column, you want to read from. Instead of doing this, you pass the name of the column. That's why you get this error message.
For more documentation, please have a look here.
I have a Windows application written in C# which connect to SQL database.
I have text fields inside my application and update the database like this:
string name = textBox60.Text;
string sql = "insert into myTable(Name) values ('" + name + "')";
DbHelper.ExecuteNonquery(sql);
public static int ExecuteNonquery(string sql)
{
using (SqlConnection cn = new SqlConnection(constr))
{
if (cn.State == ConnectionState.Closed)
{
cn.Open();
}
else if (cn.State == ConnectionState.Open)
{
cn.Close();
cn.Open();
}
else if (cn.State == ConnectionState.Broken)
{
cn.Close();
cn.Open();
}
using (SqlCommand cm = new SqlCommand(sql, cn))
{
return cm.ExecuteNonQuery();
}
}
}
But for every data with type nchar in the database, they are full of white spaces. For example if I fill in abc in the text field, when I check the database it will become "abc___________________" (white spaces) something like this.
How to prevent this other than trim the string only when I read them or to use UPDATE data SET TRIM(data) if I have tons of such data.
Thanks for help.
But for every data with type nchar in the database, they are full of whitespaces.
Yup, that's because the nchar type is a fixed-width type. You're basically telling the database that you want every value for that field to have a length of 20 (or whatever it's set to). You should use nvarchar instead, which is a variable width field.
You should also avoid writing code like this:
string sql = "insert into myTable(Name) values ('" + name + "')";
Instead, you should use parameterized SQL, putting a placeholder parameter in the SQL itself, and then setting the value for the parameter in the command. This will avoid SQL injection attacks, data conversion issues, and keep your code (the SQL) cleanly separated from the data (the parameters). It will mean you need to change your helper method though. (Your helper method looks pretty odd to start with - surely when you've just created your connection, you just need to open it... is that code left over from a time when you didn't create a new connection object on each call?)
Because you've declared the database table using a char(n) rather than a varchar(n), it is always a fixed length, and if you provide a shorter string, then it will be padded with spaces.
If you don't want the spaces, declare the column as varchar(n).
Also, I'm not sure what all of the ceremony is that you're doing with the connection before you use it, but it seems mostly pointless. You've just called new SqlConnection(...). Practically by definition, this means that cn will be closed - there's no need to check its status. Just call Open() on it and move on to creating your command.
(All of the above is predicated on the column being declared as char(n). If it's nchar(n) then you should switch to nvarchar(n)).