I have following code for deleting a value from database:

조회 수: 3 (최근 30일)
Athfin I
Athfin I 2019년 5월 3일
댓글: Athfin I 2019년 5월 4일
a=get(handles.edit1,'String');
a=convertCharsToStrings(a);
sql=['delete from student where usn=''',a]
curs=fetch(conn,sqlquery);
  댓글 수: 1
Walter Roberson
Walter Roberson 2019년 5월 3일
User's tag says,
this code gives error for value of a='4cs012' as: expected input to be string scalar or character vector

댓글을 달려면 로그인하십시오.

답변 (1개)

Walter Roberson
Walter Roberson 2019년 5월 3일
You converted a to string data type. When you use [character_vector, string_object] then it converts the character vector to a string object and then forms the nonscalar string array, which is not valid for conn.
Either do not convert a to string object or else use string concatenation which is the + operation
'delete from etc' + a
By the way, you are more likely to be successful if you remember the " character that is needed to terminate the command that is sent, to match the one just before you drop in the variable.
  댓글 수: 3
Guillaume
Guillaume 2019년 5월 3일
편집: Guillaume 2019년 5월 3일
At this point, the problem is nothing to do with matlab. You need to learn to write valid SQL queries. In particular, in SQL string literals needs to be enclosed in single or double quotes. The error message you get is entirely correct, if 4cs012 is not enclosed in quotes in the query, then it is interpreted as a column name.
SQL statements also need to be terminated with a semicolon.
Probably the easiest way to build your query is with:
sql = sprintf('delete from student where usn = "%s";', a);
<rant> The biggest problem with your code is that it's open to SQL injection. I don't understand why people are stll taught to build SQL queries that depend on user input this way instead of using prepared statements which are not vulnerable to SQL injection. If a user enters "; drop table student;-- in your edit control, they will have deleted your table. (famous XKCD published 12 years ago, and people still do it!) </rant over>
Athfin I
Athfin I 2019년 5월 4일
Thanks a lot. That worked for me, but semicolumn wasn't necessary.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by