Oracle to_date function with parameter doesn't work when trying to insert data - sql

I am trying to write basic insert statement. I have columns with date type. In C# I get datetimepicker value and convert it to string, then try to insert it with to_date. But it shows ORA-01756: quoted string not properly terminated. I found question related to this error, but it is not the same with my case. What is wrong with my script:
"Insert Into Booklets (id, exam, number_of_booklets, who_gave, when_gave, return_date) values(booklet_seq.NEXTVAL, '" + exam + "', '" + bookletNumbers + "', '" + whoGaveId + "', '" + "to_date(" + gaveTime + ", 'DD/MM/YYYY'))"

As Abra mentioned, you are ending up with
values ( ...., to_date(20/01/2020,'DD/MM/YYYY'), ... )
when you need to have
values ( ...., to_date('20/01/2020','DD/MM/YYYY'), ... )
but please, please, please do not proceed with the formatting of a SQL statement in this way if this is going to be building a true application for your workplace.
Building SQL statements by concatenation is probably the number 1 way people get hacked.
Here's a video I did on this, showing that there are tools out there that can hack your application in just a few minutes the moment you head down this path
https://youtu.be/GRh800IvllY
Binding makes your SQL immune to such hacks, eg
string sql = "select department_name from departments where department_id = " +
":department_id";
OracleCommand cmd = new OracleCommand(sql, conn);
cmd.CommandType = CommandType.Text;
OracleParameter p_department_id = new OracleParameter();
p_department_id.OracleDbType = OracleDbType.Decimal;
p_department_id.Value = 20;
cmd.Parameters.Add(p_department_id);

Related

MS Access SELECT query DatePart

i have some problem with my SELECT Query to MS Access .mdb file.
i am using VB.Net and have to send query like..
"SELECT d_date, d_tons, d_qty, d_cost FROM [deal] WHERE DatePart(""m"", [d_date]) = '" _
+ DTP.Value.Month.ToString + "' AND ([d_client] = '" + cBoxClient.Text + "')"
But it doesn't work.. No Error in compiling but this Query cannot SELECT any data.
DTP is DateTimePicker, i select Month with DTP and filled some text into cBoxClient(ComboBox)
What's wrong with that Query? i have no idea because i always used MySQL and this is my first application development with MS Access..
Please HELP me.
Use parameterized query, that will save you from sql injection and complexity of converting specific data format (such as DateTime) to it's string representation that is valid according to database specific culture. For example :
Dim queryString = "SELECT d_date, d_tons, d_qty, d_cost FROM [deal] WHERE " & _
"DatePart(""m"", [d_date]) = ? AND ([d_client] = ?)"
OleDbCommand cmd = New OleDbCommand(queryString, connection)
cmd.Parameters.AddWithValue("#date", DTP.Value.Month)
cmd.Parameters.AddWithValue("#client", cBoxClient.Text)

Insert Into Select SQL Server

I am trying to do a kind of insert into select statement. I want to insert one column as standard and the second through a select. However this is not working:
queryString = "INSERT INTO Words (Word, SortedId) VALUES ('" + words[i] + "', (SELECT TOP 1 SortedId FROM SortedWords WHERE SortedWord = '" + sortWord(words[i]) + "'))";
SortedWords is already filled with data. But at the moment i get this error
{"There was an error parsing the query. [ Token line number = 1,Token line offset = 50,Token in error = SELECT ]"}
Note:
not sure if i need the TOP 1 bit or not, get error either way. But I obvs only want to insert one row.
Change your query to
queryString = "INSERT INTO Words (Word, SortedId) SELECT '" + words[i] + "', (SELECT TOP 1 SortedId FROM SortedWords WHERE SortedWord = '" + sortWord(words[i]) + "')";
Also, instead of concatenating strings to get your query, use parameters to avoid SQL injection.
Try next and better practice to use a SqlParameters:
INSERT INTO words
(word,
sortedid)
(SELECT TOP 1 #Word,
sortedid
FROM sortedwords
WHERE sortedword = #SortedWord)
And before execiting query create a parameters(C#)
//Assume you have a SqlCommand object(lets name it command)
command.Parameters.AddWithValue("#Word", words[i]);
command.Parameters.AddWithValue("#SortedWord", sortWord(words[i]));

SQL output as variable in VB.net

I cannot seem to figure out how to get an output of a SQL query as a variable in VB. I need something like what's below so that I can use that variable in another SQL query. SQL doesn't allow the use of variables as column headers when running queries, so I thought I could use VB to insert the actual output of one SQL task as the dynamic variable in a loop of update queries. Let me (hopefully) explain.
I have the following query:
DECLARE #id int = (SELECT max(id) FROM [views]), #ViewType nvarchar(3);
WHILE #id IS NOT NULL
BEGIN
SELECT #ViewType = (SELECT [View] FROM [views] WHERE id = #id);
UPDATE a
SET a.[#ViewType] = '1'
FROM [summary] a
INNER JOIN [TeamImage] b
ON a.[Part_Number] = b.[PartNum]
WHERE b.[View] = #ViewType;
SELECT #id = max(id) FROM [views] WHERE id < #id;
END;
The SET a.[#ViewType] = '1' obviously will not work in SQL. But if I could have the (SELECT [View] FROM [views] WHERE id = #id) equal to a variable, then I could write the SQL query in VB and execute it and the variable would become part of the string and therefore execute correctly.
I'm newer to VB, but here's what I have so far:
Dim cn As SqlConnection = New SqlConnection("Data Source=Server1;" & _
"Initial Catalog=DB1;" & _
"Integrated Security=SSPI")
cn.Open()
Dim cmd As New sqlCommand("SELECT max(id) FROM orientation_view_experiment;", cn)
vID = cmd.ExecuteNonQuery()
Do While vID > 0
Dim cmd2 As New sqlCommand("SELECT [View] FROM [views] WHERE id ='" + vID + "'"
vViewType = cmd2.ExecuteNonQuery()
Dim cmd3 As New sqlCommand("UPDATE a
SET a.'" + vViewType + "' = '1' & _
FROM [summary] a & _
INNER JOIN [TeamImage] b & _
ON a.[Part_Number] = b.[PartNum] & _
WHERE b.[View] = '" + vViewType + "';"
cmd3.ExecuteNonQuery()
vID = vID - 1
Loop
cn.Close()
I hope some of that made sense, but I'm kind of lost at this point. I feel like I know what I need the SQL to do, but can't quite figure out how to make the computer/programs submit to my will and just do what I need it to do.
Thank you for any help/direction you can give.
Your code is wrong because you insist in using ExecuteNonQuery for SELECT statements. ExecuteNonQuery doesn't return the rows selected but just a count of the rows affected by an INSERT/DELETE/UPDATE query (I think that for SELECT it returns always zero)
What you need is ExecuteScalar to get the MAX value and the VIEW value because ExecuteScalar is the best choice when you expect to get just the first field of the first row from your SQL statement
Dim cmd As New sqlCommand("SELECT max(id) FROM orientation_view_experiment;", cn)
vID = Convert.ToInt32(cmd.ExecuteScalar())
Do While vID > 0
Dim cmd2 As New sqlCommand("SELECT [View] FROM [views] WHERE id =" + vID.ToString()
Dim result = cmd2.ExecuteScalar()
if Not string.IsNullOrEmpty(result)) Then
vViewType = result.ToString()
Dim cmd3 As New sqlCommand("UPDATE a SET a.[" + vViewType + "] = '1' " & _
"FROM [summary] a " & _
"INNER JOIN [TeamImage] b " & _
"ON a.[Part_Number] = b.[PartNum] " & _
"WHERE b.[View] = #vType"
cmd3.Parameters.AddWithValue("#vType", vViewType)
cmd3.ExecuteNonQuery()
End If
Loop
The last part of your code is not really clear to me, but you could use a couple of square brackets around the column name in table summary and a parameter for the View field in table TeamImage.
As a last advice, be sure that the column View in table TeamImage is not directly modifiable by your end user because a string concatenation like this could lead to a Sql Injection attacks
Do a little research into what the different methods of a command are. When you call ExecuteNonQuery, this return the number of records effected. I think you want ExecuteScalar as your cmd and cmd2 methods, so you can get a value from the database.
Have you tried replacing '" + vViewType + "' with [" + vViewType + "] ... in other words use square brackets to delimit the column name instead of single quotes which are for delimiting string literals?
Also, I would encourage stopping in the debugger, examining the command that you generated into cmd3 and try executing it directly. It might help you identify other similar problems such as the fact that vViewType is giving you a count of records instead of an actual value from the [View] column.

String or binary data would be truncated. The statement has been terminated

I always got an error when adding a new data. the error says
String or binary data would be truncated. The statement has been terminated
As I've looked back on my backend or code. It looks like there's a conflict adding a TWO LABEL DATA in one column because I would like to join the (Year)-(StudentNumber)
Here's the code of my INSERT INTO Statement
INSERT INTO
[Student_Information] (StudentID, LastName, FirstName, MiddleName, Gender,
ContactNumber, Citizenship, Religion, Birthday, Address)
VALUES
( '" & lbl_cyear.Text - studid.Text & "','" + txt_lname.Text + "', '" + txt_fname.Text + "', '" + txt_mname.Text + "', '" + DDGender.Text + "', '" & txt_cnumber.Text & "', '" & txt_citizenship.Text & "' , '" + txt_religion.Text + "' , '" & txt_bday.Text & "', '" & txt_address.Text & "' )"
and here's the code how I generate the Year and the Student Number
Sub SNYear()
Dim test As Date
test = Convert.ToDateTime(Today)
lbl_cyear.Text = test.Year
End Sub
Sub SNGenerate()
'displaying Studentid
Dim SN As Integer ' Student Number
Dim SID As String 'Student ID Num as String
Dim rdr As SqlDataReader
cmd1.Connection = cn
cmd1.Connection.Open()
cmd1.CommandText = "Select Max (StudentID) as expr1 from [Student_Information]"
rdr = cmd1.ExecuteReader
If rdr.HasRows = True Then
rdr.Read()
End If
If rdr.Item(0).ToString = Nothing Then
SN = rdr.Item(0) + 1
SID = Format(SN, "0000")
ElseIf rdr.Item(0).ToString = 0 Then
SN = rdr.Item(0) + 1
SID = Format(SN, "0000")
Else
SN = rdr.Item(0) + 1
SID = Format(SN, "0000")
End If
studid.Text = SID
cmd1.Connection.Close()
End Sub
Can someone help me with the code? How to join 2 data in different label text and save it to one column in my table.
Woah! Never ever write sql queries like that. It's subject to dangerous SQL injection, and code like that is actually used as worst-case scenarios in SQL injection lectures everywhere!
That being said, the error message String or binary data would be truncated. The statement has been terminated. actually spells out what is wrong. You are trying to insert too much data into a field that has a specific dimension.
You are trying to insert the following expression into the StudentID field:
lbl_cyear.Text - studid.Text
I'm not even sure what you want to do there. Since Visual Basic is loosely typed by default, It will probably handle the lbl_cyear.Text as a number and try to subtract the studid.Text (as a number) from it. You probably mean something like this:
lbl_cyear.Text & "-" & studid.Text
It seems you are trying to use the StudentID column for two different types of information. Don't do that. Decide on one format for the student ids and dimension the column for it.
Is this a homework assignment?
Y#atornblad has some very valid points about re-structuring your code. However, the specific problem you are asking about is likely because you are trying to insert data into a column that is longer than the column can accept.
E.g. - you are trying to insert "Lorem Ipsum" into a column that has a maximum length of 5 characters.
Edit
You need to take another look at how your table is defined and make sure it is appropriate for the data you are storing. Also - make sure the data you are trying to store is in the correct format that the table was designed for. Don't assume it's in the format you want, actually step through the program in debug mode and look at what the variable is before it gets sent to the database.

How to save integer to sql column with data type int [duplicate]

This question already has answers here:
Problem with querying sql server from vb
(3 answers)
Closed 2 years ago.
i am having this problem for quite some time now and cannot figure out the solution..
i have a productid that i get as a result of sql query. The data type of productid in database is int
Dim scheduleid As Integer
cmd.CommandText = "Insert into DeploymentSchedules (scheduleName) values('Schedule');select Scope_Identity();"
scheduleid = cmd.ExecuteScalar()
Now when i want to insert it into another table ...
cmd.CommandText = "Insert into
locationsSchedule(LocationName,length,width,height,floor,walls,permIeter,scheduleid)
values('" + strRoomName + "','" + txtLength.Text + "','" + txtWidth.Text + "','" +
txtHeight.Text + "','" + wallSTring + "','" + floorString + "','" + perimeterStrin +
"','" + scheduleid + "')"
cmd.ExecuteScalar()
I am having error
Conversion from string "Insert into locationsSchedule(Lo" to type 'Double'
is not valid.
I know it has something to do with integer as when i remove product id it is working .Please help
THank you
You have ' around your scheduleid which will cast the int to string. Remove them and all should be fine (maybe you have to do this for other columns also):
"'," + scheduleid + ")"
BTW: Ever heard of SQL-Injection?
Does changing from
cmd.ExecuteScalar()
to
cmd.ExecuteNonQuery()
remove the error for you?
In your first example you are returning the recently created unique id for the row. In the second query you're not. Either change as shown here or return an integer from your query.
Oh, and look at other ways of building SQL strings (parametrised queries!)