c # ado, net을 사용하여 SQL Server 데이터베이스에 행 삽입 시도
Nov 24 2020
키보드에서 입력을 읽고있는 콘솔 응용 프로그램에서 Ado.Net을 사용하여 SQL Server 데이터베이스에 행을 삽입하려고합니다 ....
내 코드는 다음과 같습니다.
private void InsertStudents(string con)
{
SqlConnection Connection = new SqlConnection(con);
SqlDataAdapter adapter = new SqlDataAdapter();
int id = Convert.ToInt32(Console.ReadLine());
string firstName = Console.ReadLine();
string lastName = Console.ReadLine();
DateTime dateOfBirth = Convert.ToDateTime(Console.ReadLine());
double tuitionFees = Convert.ToDouble(Console.ReadLine());
string sql = "$insert into product (ID,FirstName,LastName,DateOfBirth,TuitionFees) values {id}, {firstName}, {lastName}, {dateOfBirth}, {tuitionFees})";
try
{
Connection.Open();
adapter.InsertCommand = new SqlCommand(sql, Connection);
adapter.InsertCommand.ExecuteNonQuery();
Console.WriteLine(" 1 Row inserted!");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
내 문제는 컴파일러가 내 보간 된 문자열을 문자열로 읽지 만 열을 변수로 인식하지 않는다는 것입니다. 전체 줄을 단일 문자열로 읽습니다. 무엇이 문제입니까?
답변
3 MarcGravell Nov 24 2020 at 10:41
이것은 매우 중요합니다. SQL에 보간 된 문자열을 사용 하지 마십시오 . 그것은 모든면에서 나쁜 :
- 보안 : SQL 주입
- 성능 : 쿼리 계획 재사용
- 신뢰성 : 다음과 같은 예약 된 기호의 취성
'
- 정확성 : i18n / l10n (즉, 형식화) 문제-특히
DateTime
값 (생년월일, "07/11/2020"이 11 월 7 일입니까? 또는 7 월 11 일입니까?)-수업료 금액 ( "123,456", 쉼표가 소수점 구분 기호 (France et al)입니까? 아니면 그룹 구분 기호입니까?)
올바른 접근 방식은 매개 변수 입니다. 항상.
따라서 SQL은 다음과 같습니다.
insert into product (ID,FirstName,LastName,DateOfBirth,TuitionFees)
values (@id, @firstName, @lastName, @dateOfBirth, @tuitionFees)
그리고, 그렇게 하나하는 ADO.NET 매개 변수에 대한 자세한 내용, 또는 : 같은 도구를 사용하여 단정 한 그 단순화 그것은 :
int id = ...
string firstName = ...
string lastName = ...
DateTime dateOfBirth = ...
double tuitionFees = ...
using var conn = new SqlConnection(con); // Dapper will deal with the open/close
conn.Execute(@"
insert into product (ID,FirstName,LastName,DateOfBirth,TuitionFees)
values (@id, @firstName, @lastName, @dateOfBirth, @tuitionFees)",
new { id, firstName, lastName, dateOfBirth, tuitionFees });
또한 마지막 참고 사항 : double
통화 에는 사용하지 마십시오 . 를 사용하십시오 decimal
. double
통화 금액에 적합하지 않습니다.
jason.kaisersmith Nov 24 2020 at 09:49
달러 기호를 문자열 앞이 아니라 문자열 안에 넣었습니다. 그것은해야한다:
string sql = $"insert into product (ID,FirstName,LastName,DateOfBirth,TuitionFees) values {id}, {firstName}, {lastName}, {dateOfBirth}, {tuitionFees})";