Spring에서 Oracle을 연결할경우에는 mvc 모델을 사용하여서 통합설정 config에서 오라클 db의 계정 비밀번호를 입력하여 mapper를 설정해주면 됐지만, Web Forms에서는 .net을 활용하고, 비주얼 스튜디오 자체에 sql 연결하는 탭이 잘 돼있어서 익숙하지 않아도 쉬울거라 생각했다.
솔루션 탐색기가 아닌 서버 탐색기에서 데이터 베이스 서버를 추가하는 버튼을 누르면 설정탭이 나온다.
여러가지 방법이 있겠지만, 이것저것 시도해본 결과 결국 오류가 나지 않는 방법을 택하게됐다. 이 창을 올려놓은 후 MS-SQL 서버 매니지먼트에서 작업을 계속한다.
내 SQL서버를 접속할때 사용한 서버이름을 기록해두자. 이곳에 들어가는 서버이름이, VS에서도 사용된다.
MS-SQL을 로그인 한 후에 새로운 데이터베이스를 만든다. 학생 정보를 입력받는 폼을 만들어서 이름,나이,주소,소개 정도만 저장을 해줄 생각이다.
Student_Info 라는 테이블에 StudentID,Name,Address,Age,Contact 칼럼을 만들었다. 더이상 ms-sql에서 건드릴 부분은 없다.
ms-sql 서버 로그인에 보였던 서버이름과, 사용자이름, 암호/ 혹은 윈도우 로그인도 가능하다. 를 입력한 후에 하단에 데이베이스를 선택하고 연결을 누르면 설정끝이다. programmingDB를 새로 만들고 그 아래에 테이블을 만들었기 때문에 각자 다른방법으로 나올것이다.
연결이 끝났다면 확인후에 aspx, cs를 완성해주자
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="user-form.aspx.cs" Inherits="test_project.user_form" %>
<%@ Register assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" namespace="System.Web.UI.DataVisualization.Charting" tagprefix="asp" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<style type="text/css">
.auto-style1 {
width: 100%;
}
.auto-style2 {
width: 165px;
}
.auto-style3 {
width: 220px;
}
.auto-style4 {
height: 45px;
text-align: center;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="auto-style4">
학생 정보 관리 표
</div>
<table class="auto-style1">
<tr>
<td class="auto-style2"> </td>
<td class="auto-style3">StudentID</td>
<td>
<asp:TextBox ID="StudentID" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2"> </td>
<td class="auto-style3">Student Name</td>
<td>
<asp:TextBox ID="StudentName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2"> </td>
<td class="auto-style3">Address</td>
<td>
<asp:TextBox ID="Address" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2"> </td>
<td class="auto-style3">Age</td>
<td>
<asp:TextBox ID="Age" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2"> </td>
<td class="auto-style3">Contact</td>
<td>
<asp:TextBox ID="Contact" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2"> </td>
<td class="auto-style3"> </td>
<td>
<asp:Button ID="Button1" runat="server" Text="Button" Width="105px" OnClick="Button1_Click" />
</td>
</tr>
<tr>
<td class="auto-style2"> </td>
<td class="auto-style3"> </td>
<td> </td>
</tr>
<tr>
<td class="auto-style2"> </td>
<td class="auto-style3"> </td>
<td>
<asp:GridView ID="GridView1" runat="server" Width="458px">
</asp:GridView>
</td>
</tr>
</table>
</form>
</body>
</html>
작성한 디자인폼의 소스코드. 하단의 표는 데이터베이스에 저장된 정보를 불러들일때 사용할 것이고, 그 위는 입력받을 폼이다. TextBox의 이름을 데이터베이스 칼럼명과 일치해주는것이 보기 좋기때문에 수정하였다. 수정하지 않아도 가능하다. 입력된 정보는 button을 눌렀을때 데이터베이스로 쏴준다. ( OnClick )
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-F3TPC61;Initial Catalog=programmingDB;User ID=계정;Password=비밀번호");
con.Open();
SqlCommand comm = new SqlCommand("Insert into Student_Info values('" + int.Parse(StudentID.Text) + "','" + StudentName.Text + "','" + Address.Text + "','" + double.Parse(Age.Text) + "','" + Contact.Text + "')", con);
comm.ExecuteNonQuery();
con.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Successfully Inserted');", true);
}
결과적으로는 해당 코드가 데이터베이스에 데이터를 쏴줄 수 있는 코드이다. 한 줄 한 줄 해석해보자, 응용해서 나중에도 사용해보자
SqlConnection con = new SqlConnection("Data Source=DESKTOP-F3TPC61;Initial Catalog=programmingDB;User ID=아이디;Password=비밀번호");
SqlConnection 은 .Net에서 지원하는 키워드다.
()내부에 "Data Souerce"의 정보는 연결된 데이터 베이스에 연결문자열에서 알아낼 수 있다.
해당 연결 문자열을 모두 복사하여 붙여넣으면 password가 ****로 나오기때문에 수정해주어 사용한다. 해당 문구가 정확하지 않으면 데이터베이스에 연결이 되지않기 때문에 오류를 출력한다.
con.Open();
SqlCommand comm = new SqlCommand("Insert into Student_Info values('" + int.Parse(StudentID.Text) + "','" + StudentName.Text + "','" + Address.Text + "','" + double.Parse(Age.Text) + "','" + Contact.Text + "')", con);
comm.ExecuteNonQuery();
con.Close();
그 밑은 네줄까지 통쨰로, sql을 열고, Command 키워드로 쿼리문을 쏴준다. insert into 테이블명 values(칼럼명 대응); 은 데이터베이스 정보 입력의 기본 문구이다. ExecuteNonQuery()는 연결에 대한 Transact-SQL 문을 실행하고 영향을 받는 행의 수를 반환한다. 그 후에 데이터베이스를 닫아주면서 문구가 끝난다.
ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Successfully Inserted');", true);
마지막은 ScriptManager를 통해 성공했을 경우 경고창을 띄워주는 역할이다.
성공시 해당 경고창이 잘 뜨는것을 확인하고, 데이터베이스에서 정보가 잘 넘어왔는지도 확인한다.
간단할 줄 알았는데, 연동하는데만 2시간은 잡아먹었다
'C#' 카테고리의 다른 글
22.11.29 C# 일지_4 (0) | 2022.11.29 |
---|---|
Asp .Net Web Forms - 04. MS-SQL 데이터 불러오기 (0) | 2022.11.28 |
asp .net web forms - 02. 회원가입 폼 (0) | 2022.11.28 |
asp .net web forms - 01. 시작하기 (0) | 2022.11.28 |
22.11.23 C# 일지_3 (0) | 2022.11.23 |