“Column count doesn't match value count at row 1” - c#

I've looked at different links (like this one), but i still can't get where does this error message comes from. I keep on counting columns, comas and so on without finding where is the problem.
int exId = stride.getExerciseId();
string timestamp = stride.getTimeStamp();
int startSec = stride.getBeginningSec();
int startMsec = stride.getBeginningMSec();
int endSec = stride.getEndSec();
int endMSec = stride.getEndMSec();
float length = stride.getLength();
float duration = stride.getDuration();
float steplength = stride.getStepLength();
float stepDuration = stride.getStepDuration();
string supportingFoot = stride.getSupportingFoot();
string query = "INSERT INTO singlesupportstate (ExerciseId , TimeStamp , SingleSupportStateStartSeconds , SingleSupportStateStartMSeconds , SingleSupportStateEndSeconds , SingleSupportStateEndMSeconds , StrideLength , StrideDuration , StepLength , StepDuration , SupportingFoot)
VALUES("+ exId +",'" + timestamp +"',"+ startSec +"," + startMsec + "," + endSec + "," + endMSec + "," + length +"," + duration + "," + steplength + "," + duration + ",'" + supportingFoot + "')";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
this.CloseConnection();
}
EDIT :
So I changed my code in order to use Parameterized query, here is the new code that works:
if (this.OpenConnection() == true)
{
MySqlCommand cmd = connection.CreateCommand() ;
cmd.CommandText = "INSERT INTO singlesupportstate (ExerciseId , TimeStamp , SingleSupportStateStartSeconds , SingleSupportStateStartMSeconds , SingleSupportStateEndSeconds , SingleSupportStateEndMSeconds , StrideLength , StrideDuration , StepLength , StepDuration , SupportingFoot) "
+" VALUES(#exId,#timestamp,#startSec,#startMsec,#endSec,#endMSec,#length,#duration,#steplength,#stepduration,#supportingFoot)";
cmd.Parameters.Add("#exId", MySqlDbType.Int32);
cmd.Parameters.Add("#timestamp",MySqlDbType.Timestamp);
cmd.Parameters.Add("#startMsec",MySqlDbType.Int32);
cmd.Parameters.Add("#startSec",MySqlDbType.Int32);
cmd.Parameters.Add("#endSec",MySqlDbType.Int32);
cmd.Parameters.Add("#endMSec",MySqlDbType.Int32);
cmd.Parameters.Add("#length", MySqlDbType.Float);
cmd.Parameters.Add("#duration",MySqlDbType.Float);
cmd.Parameters.Add("#steplength",MySqlDbType.Float);
cmd.Parameters.Add("#stepduration", MySqlDbType.Float);
cmd.Parameters.Add("#supportingfoot", MySqlDbType.Text);
cmd.Parameters["#exId"].Value = exId;
cmd.Parameters["#timestamp"].Value = timestamp;
cmd.Parameters["#startMsec"].Value = startMsec;
cmd.Parameters["#startSec"].Value = startSec;
cmd.Parameters["#endSec"].Value = endSec;
cmd.Parameters["#endMSec"].Value = endMSec;
cmd.Parameters["#length"].Value = length;
cmd.Parameters["#duration"].Value = duration;
cmd.Parameters["#steplength"].Value =steplength;
cmd.Parameters["#stepduration"].Value =stepDuration;
cmd.Parameters["#supportingfoot"].Value =supportingFoot;
cmd.CommandTimeout = 120;
cmd.ExecuteNonQuery();
this.CloseConnection();
}

This means that in one of the values in the concatenation is breaking the INSERT because it has a comma or string delimiter, thus breaking the whole query string
Look at the actual query string after concatenation, before execution
And use parameters to remove this problem anyway and mitigate SQL injection risks.
The other option is a trigger (saym for audit or history) on the singlesupportstate table that has a broken INSERT too.

What is likely happening is one of two things:
1) There are ' quotes making your query seem it has fewer values, because it eats up the commas.
2) There are numbers being formatted with a comma rather than a point, resulting in the number 123.45 showing as 123,45, thus making the query think there are two integer values: 123 and 45 resulting in too many values.
As others have said, try and use query parameters and this won't happen again. It also saves you a lot of manual escaping of strings.

Related

CSV - Import file to a Sql database through code

I need to load data from text file/csv file to a SQL Server database. I used the code shown below to load data and is loading to the database the problem is the data in second column may contain space but I use space for separate the column data.
i.e.
200007 XXXX Check XXXX yyy 50
200013 YYYY Check ZZZZ yyy 50
200022 nnnn 25Mg 30 Tabs
200042 mmmm 30 Mg 30 Tabs
I need to store the first ID number in the first column and the remaining text in second column:
string str = Properties.Settings.Default.con;
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = con;
con.Open();
cmd.CommandText = "IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='TEMP_AUTO' AND xtype='U')" +
"CREATE TABLE TEMP_AUTO (" +
"ID varChar(10) NULL," +
"NAME varChar(50) NULL," +
"DATE TIMESTAMP NULL," +
")";
cmd.ExecuteNonQuery();
string query1 = "INSERT INTO [dbo].[TEMP_AUTO]([ID],[NAME]) VALUES (#num1, #num2)";
cmd.CommandText = query1;
string[] allLines = File.ReadAllLines(txtFilePath.Text);
for (int i = 0; i < allLines.Length; i++)
{
cmd.Parameters.Clear();
string[] items = allLines[i].Split(new char[] { ' ' });
cmd.Parameters.AddWithValue("#num1", items[0]);
cmd.Parameters.AddWithValue("#num2", items[1]);
cmd.ExecuteNonQuery();
}
MessageBox.Show("Successfully saved your data");
}
finally
{
cmd.Dispose();
con.Close();
}
A possible solution might be this:
string[] allLines = {
"200007 XXXX Check XXXX yyy 50",
"200013 YYYY Check ZZZZ yyy 50",
"200015 ",
"2541111"
};
for (int i = 0; i < allLines.Length; i++)
{
string param1 = null;
string param2 = null;
int spaceIndex = allLines[i].IndexOf(' ');
if (spaceIndex > 0)
{
param1 = allLines[i].Substring(0, spaceIndex);
if (spaceIndex < allLines[i].Length - 1)
{
param2 = allLines[i].Substring(spaceIndex + 1, allLines[i].Length-1 - spaceIndex);
}
}
else
{
param1 = allLines[i];
}
Console.WriteLine("param1:{0} param2:{1}", param1, param2);
}
Use SSIS to map this file as long as it has a standard structure to SQL Table.
Is this a one time thing? Have you tried getting the data organized in Excel then using the SSMS import tool to bring it in? If you right click on the Database then Tasks > Import Data the wizard will appear when given the option to choose the source, choose Excel. Flat files is an option but if you can format it in Excel first that tends to work better.
As you click through you can adjust the column types and where the breaks are, much like importing into Excel itself.
Use the String.Split(Char[], Int32) method to split on the first occurrence of ' ' only. Eg
string[] items = allLines[i].Split(new char[] { ' ' }, 2);
Refs: MSDN and previous relevant question
Use the below code.
using (StreamReader sr = File.OpenText("txtFile.txt")) // Mention the path,if the file is not in application folder.
{
string str = String.Empty;<br/>
while ((str = sr.ReadLine()) != null)
{
string[] item = str.Split(' ');
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand();
string query1 = "INSERT INTO [dbo].[TEMP_AUTO]([ID],[NAME]) VALUES ('" + item[0] + "', '" + item[1] + "')";
// Do remain part<br/>
}
}

c# sql wildcard not working

I am attempting to use "%" in order to search for a range of dates. In the table the dates are of the format "03/01/2015" and I am trying to return data for all dates of a specific month (03/2015 for example).
I am creating two strings of the format...
String datePrev1 = monthLast + "%";
String datePrev2 = "%" + yearLast;
Where datePrev1 == "03%" and datePrev2 == "%2015" which I have confirmed to be generating correctly.
My SQL search method is...
SqlCommand selectCommand = new SqlCommand("SELECT project, prevWeekHours FROM submissionsHours WHERE (WWID = '" + ID + "' AND (datePrevWeek LIKE '" + datePrev1 + "' AND datePrevWeek LIKE '" + datePrev2 + "'))", Conn1);
Conn1.Open();
SqlDataReader reader = selectCommand.ExecuteReader();
int totalTime = 0;
while (reader.Read() == true)
{
project.Add(reader[0].ToString());
projTime.Add(Convert.ToInt32(reader[1]));
totalTime += Convert.ToInt32(reader[1]);
}
Conn1.Close();
int index = project.Count; //total amount of projects
testLabel.Text = index.ToString() + "..." + datePrev1+datePrev2;
The testLabel.Text I have for troubleshooting is returning 0 for the index indicating there were no matches for this string when there are certainly entries in the table that should match it.
Any ideas on what I am doing wrong?
I have attempted querying like...
... WHERE datePrevWeek LIKE '03/__/2015';
... WHERE datePrevWeek LIKE '03____2015';
To no success... Thanks.
SELECT project, prevWeekHours
FROM submissionsHours
WHERE WWID = #ID
AND (YEAR(datePrevWeek)*100)+MONTH(datePrevWeek) = #YEARMONTH
#YEARMONTH should be of format 201503 representing march 2015.
Using parameters will avoid sql injection.
When datePrevWeek is varchar
SELECT project, prevWeekHours
FROM submissionsHours
WHERE WWID = #ID
AND right(datePrevWeek,7) = #YEARMONTH_STR
#YEARMONTH_STR is of format '01/2015'
Once you store dates in the format '2015-03-13',...
Plan A: WHERE dt LIKE '2015%'
Plan B (This is more efficient, given a suitable index):
WHERE dt >= CONCAT('2015', '-01-01')
AND dt < CONCAT('2015', '-01-01') + INTERVAL 1 YEAR
(I'm assuming '2015' is filled in by the code.)
Try Below:
Declare #Dat Date
set #Dat = '03/01/2015'
SELECT CAST(MONTH(#Dat) AS VARCHAR(2)) + '/' + CAST(YEAR(#Dat) AS VARCHAR(4)) AS [DD/YYYY]

all_ind_expressions view of Oracle

I'm trying to execute the below query through OracleDataReader in .NET but when I try to read the value of the column_expressions column, I always get an empty string.
SELECT ic.column_name,
ie.column_expression
FROM all_ind_columns ic
LEFT JOIN all_ind_expressions ie
ON ie.index_owner = ic.index_owner
AND ie.index_name = ic.index_name
AND ie.column_position = ic.column_position
WHERE ic.index_owner = 'owner_name'
AND ic.index_name = 'index_name'
I realized that the datatype of the column id is LONG but I'm not sure if that's the reason. Is there a way I can read the actual value of the column?
When I execute the same query through Oracle SQL developer, I can see the value.
To be able to read a column that is of LONG data type the InitialLONGFetchSize property of OracleCommand has to be set to a none zero(zero by default) value:
Unfortunately you did not provide your .NET code, so I'll give you a C# + ODP.NET unmanaged driver example:
Set-up:
create table t1(
col1 varchar2(11)
);
create index FBI on t1(upper(col1));
table T1 created.
index FBI created.
C# code:
string oraConnectionString = "Data source=nkpdb;User id=hr;password=password;";
OracleConnection oraConnection = new OracleConnection(oraConnectionString);
oraConnection.Open();
/* Would be better to put this in a stored procedure */
string sqlQuery = "select ic.column_name " +
" , ie.column_expression " +
" from all_ind_columns ic " +
" left join all_ind_expressions ie " +
" on ie.index_owner = ic.index_owner " +
" and ie.index_name = ic.index_name " +
" and ie.column_position = ic.column_position " +
" where ic.index_owner = :INDOwner " +
" and ic.index_name = :INDName" ;
OracleCommand oraCmd = new OracleCommand(sqlQuery, oraConnection);
OracleParameter indOwner = new OracleParameter("INDOwner",
OracleDbType.Varchar2);
OracleParameter indName = new OracleParameter("INDName",
OracleDbType.Varchar2);
indOwner.Value = "HR";
indName.Value = "FBI";
oraCmd.Parameters.Add(indOwner);
oraCmd.Parameters.Add(indName);
/* set up initial amount of data that the OracleDataReader
* fetches for LONG column */
oraCmd.InitialLONGFetchSize = 1000; /* set initial size */
OracleDataReader oraDataReader = oraCmd.ExecuteReader();
if (oraDataReader.HasRows)
{
while (oraDataReader.Read())
{
Console.WriteLine(oraDataReader.GetString(
oraDataReader.GetOrdinal("column_expression")));
}
}
Result:
By default the InitialLONGFetchSize property is set to 0. That's the reason why you are getting an empty string. So you either need to set this property to a value greater than zero or set it to -1 to fetch an entire LONG column.
Here 's another simple solution.
1 - Create this function
create or replace function Get_Text
(sINDEX_NAME in VARCHAR2, sIndex_owner in VARCHAR2, sColumn_position in VARCHAR2)
return varchar2
is
Long_to_Varchar varchar(32767);
begin
select COLUMN_EXPRESSION into Long_to_Varchar
from SYS.all_ind_expressions
where INDEX_NAME = sINDEX_NAME and Index_owner=sIndex_owner and Column_position=sColumn_position;
return long_to_varchar;
exception
when others then
return 'Error occurred';
end;
2 - Use this SQL
select ic.index_name,
ic.column_name,
GET_TEXT(Ie.INDEX_NAME,Ie.Index_owner,ie.Column_position )
from all_ind_columns ic
left join all_ind_expressions ie
on ie.index_owner = ic.index_owner
and ie.index_name = ic.index_name
and ie.column_position = ic.column_position
WHERE ic.index_owner = 'owner_name'
AND ic.index_name = 'index_name'

Using stream reader to catch values returned by sql statemtnt c#

guys i have an SQL statement returning more than 1 value.
I am trying to use the StreamReader to get the values into an array as below
string sql = "select distinct COLUMN_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME=' " + table + "' and CONSTRAINT_NAME like 'PK_%'";
SqlConnection conn2 = new SqlConnection(cnstr.connectionString(cmbDatabase.Text));
SqlCommand cmd_server2 = new SqlCommand(sql);
cmd_server2.CommandType = CommandType.Text;
cmd_server2.Connection = conn2;
conn2.Open();
//reader_sql = new StreamReader();
SqlDataReader reader_sql = null;
string[] colName = new string[200];
reader_sql = cmd_server2.ExecuteReader();
while (reader_sql.Read());
for (int rr = 0; rr < 20; rr++)
{
colName[rr] = reader_sql["COLUMN_NAME"].ToString();
}
It is not working, what am I doing wrong guys ?
You've got a stray ; turning your while into a tight loop, so instead try:
while (reader_sql.Read())
for (int rr = 0; rr < 20; rr++)
{
colName[rr] = reader_sql["COLUMN_NAME"].ToString();
}
You get the exception because
while (reader_sql.Read());
should be
while (reader_sql.Read())
{
for (int rr = 0; rr < 20; rr++)
{
colName[rr] = reader_sql["COLUMN_NAME"].ToString();
}
}
Perhaps you should remove the semicolon at the end of Read
while (reader_sql.Read())
{
for (int rr = 0; rr < 20; rr++)
colName[rr] = reader_sql["COLUMN_NAME"].ToString();
}
However, if your intention is to retrieve the columns belonging to the primary key, your code is wrong because you add 20 times the same primary key column, then repeat the same for the remaining columns ending with an array of 20 strings all equals to the last column in the primary key set. I think you should change your code to use a List(Of String) instead of a fixed length array and let the reader loop correctly on the primary key columns retrieved
List<string> pks = new List<string>();
while (reader_sql.Read())
{
pks.Add(reader_sql["COLUMN_NAME"].ToString());
}
EDIT: I have just noticed that your query contains a space before the table name. The string concatenation then produces an invalid table name, the query is syntactically right but doesn't return any data
string sql = "select distinct COLUMN_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE " +
"where TABLE_NAME='" + table + "' and CONSTRAINT_NAME like 'PK_%'";
^ space removed here
And while you are at it, remove the string concatenation and use a parameterized query.....
string sql = "select distinct COLUMN_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE " +
"where TABLE_NAME=#tName and CONSTRAINT_NAME like 'PK_%'";
SqlCommand cmd_server2 = new SqlCommand(sql, connection);
connection.Open();
cmd_server2.Parameters.AddWithValue("#tName", table);

SQL Update not actually updating? Done

SOLVED: I figured out my own issue. It was working as I thought. I just was not reading the correct row.
I am trying to update a few columns in a row, in the Table [Profiles]. I don't get any errors when running this code but it doesn't actually update the columns. I have never used an update before. What am I doing wrong.
string currentPage = Request.Url.ToString();
Uri myUri = new Uri(currentPage);
string position = HttpUtility.ParseQueryString(myUri.Query).Get("position");
string electionYear = HttpUtility.ParseQueryString(myUri.Query).Get("year");
var finalkey = Session["Userid"].ToString() + "^" + position + "^" + electionYear;
string sqlquery = "UPDATE [Profiles] SET Qualifications=#Qualifications, Platform=#Platform, FamilyLife=#FamilyLife, Website=#Website where FinalKey=#FinalKey";
SqlConnection conn = new SqlConnection(dbLocation);
SqlCommand comm = new SqlCommand(sqlquery, conn);
try
{
conn.Open();
comm.Parameters.AddWithValue("#FinalKey", finalkey);
comm.Parameters.AddWithValue("#Qualifications", qualificationsBox.Text);
comm.Parameters.AddWithValue("#Platform", platformBox.Text);
comm.Parameters.AddWithValue("#FamilyLife", familyBox.Text);
comm.Parameters.AddWithValue("#Website", candWebsiteBox.Text);
comm.ExecuteNonQuery();
}
catch { }
conn.Close()
Please refer the value of finalkey by set break Point ! Only Possible for Not Updating is,
There is no matching record found with this finalkey value.
another option
set where class value manually Like where finalvalue="user1dec" and check if it is work, then u can........
var finalkey = Session["Userid"].ToString() + "^" + position + "^" + electionYear;

Categories