27.03.2021, 18:14. Показов 1085. Ответов 1
Здравствуйте,
Кто может подсказать где ошибка в коде.
Ошибка:
У меня имеется процедуры с переменной и данные для этой переменой берутся из input'a в form'e. Но я не могу понять где мне надо bor_surname еще обьявить что бы код заработал.
*Сама процедура и сам код работают прекрасно если удалить от туда перемемую
Таблица:
Процедурa:
| SQL |
1
2
3
4
5
6
7
| CREATE PROCEDURE [dbo].[sproc_FindBorrower]
@bor_surname CHAR(20)
AS
SELECT *
FROM tblBorrower
WHERE bor_surname = @bor_surname;
RETURN 0 |
|
Input:
| HTML5 |
1
2
3
4
5
6
7
8
| <form method="POST" action="FindBorrower.aspx">
<div>
<label for="bor_surname"> Borrower's Surname </label>
<input name="txtSurname" id="bor_surname" placeholder="Smith" />
</div>
<input type="submit" value="Search" OnClick="btnSearch_Click">
</form> |
|
Active Server Page code:
| Code |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
| <form id="form1" runat="server">
<div>
<%
string surname = Request.Form["txtSurname"];
Int32 RecordCount = 0;
Int32 ColumnCount = 0;
string ColumnName;
Int32 ColumnIndex = 0;
Int32 RecordIndex = 0;
clsDataConnection DB = new clsDataConnection();
DB.Execute("sproc_FindBorrower");
Response.Write ("<table border=1 cellpadding=4>");
Response.Write ("<tr>");
ColumnCount = DB.DataTable.Columns.Count;
while (ColumnIndex < ColumnCount)
{
ColumnName = DB.DataTable.Columns[ColumnIndex].ColumnName;
Response.Write("<td><b>" + ColumnName + "</b></td>");
ColumnIndex++;
}
Response.Write ("</tr>");
ColumnIndex = 0;
RecordIndex = 0;
RecordCount = DB.Count;
while (RecordIndex < RecordCount)
{
ColumnIndex = 0;
Response.Write("<tr>");
while (ColumnIndex < ColumnCount)
{
Response.Write("<td>" + DB.DataTable.Rows[RecordIndex][ColumnIndex] + "</td>");
ColumnIndex++;
}
RecordIndex++;
}
Response.Write ("</tr>");
Response.Write("</table>");
%>
</div>
</form> |
|
Тут я что то пробывал подключить базу данных но она и без этого передает данные из input'a в переменую surname в aspx
| C# |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace OnlineLibraryAccess
{
public partial class FindBorrower : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
/*
protected void btnSearch_Click(object sender, EventArgs e)
{
string connStr = @"Data Source=(LocalDB)\MSSQLLocalDB;Integrated Security=True;Connect Timeout=30";
SqlConnection conn = new SqlConnection(connStr);
try
{
conn.Open();
}
catch (SqlException se)
{
Console.WriteLine("Error:{0}", se.Message);
return;
}
Console.WriteLine("Succsess");
SqlCommand cmd = new SqlCommand("Select * From tblBorrower", conn);
using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
for (int i = 0; i < dr.FieldCount; i++)
Console.Write("{0}\t", dr.GetName(i).ToString().Trim());
while (dr.Read())
{
Console.WriteLine("{0}\t{1}\t{2}", dr.GetValue(0).ToString().Trim(),
dr.GetValue(1).ToString().Trim(),
dr.GetValue(2).ToString().Trim());
}
}
conn.Close();
conn.Dispose();
Console.WriteLine();
}
*/
}
} |
|
Подключение самой базы данных:
*Данный код не является моим
| C# |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data;
public class clsDataConnection
{
//connection object used to connect to the database
SqlConnection connectionToDB = new SqlConnection();
//data adapter used to transfer data to and from the database
SqlDataAdapter dataChannel = new SqlDataAdapter();
//ado.net class for building the sql commands
SqlCommandBuilder commandBuilder = new SqlCommandBuilder();
//stores a list of all of the sql parameters
List<SqlParameter> SQLParams = new List<SqlParameter>();
//data table used to store the results of the stored procedure
DataTable dataTable = new DataTable();
//string variable used to store the connection string
private string connectionString;
public clsDataConnection()
{
GetConString(GetDBName());
}
public clsDataConnection(string DBLocation)
{
GetConString(DBLocation);
}
private string GetConString(string SomePath)
{
//build up the connection string for the sql server database Visual Studio 2010
//connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=" + GetDBName() + ";Integrated Security=True;User Instance=True";
//build up the connection string for the sql server database Visual Studio 2012
//connectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=" + GetDBName() + ";Integrated Security=True;Connect Timeout=30";
//connectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"" + GetDBName() + "\";Integrated Security=True;Connect Timeout=30";
connectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"###\";Integrated Security=True;Connect Timeout=30";
connectionString = connectionString.Replace("###", SomePath);
return connectionString;
}
public string GetDBName()
{
//array to store folder names
string[] filePaths;
//var to store index for path array
Int32 PathArrayIndex = 0;
string[] dirConts;
//flag for found
Boolean Found = false;
//var for counter
Int32 Counter;
List<string> DBNames = new List<string>();
//get the folder for the project
string BaseDir = TrimPath(System.AppDomain.CurrentDomain.BaseDirectory);
do
{
//get the list of files in the folder
filePaths = System.IO.Directory.GetDirectories(BaseDir);
PathArrayIndex = 0;
while (PathArrayIndex < filePaths.Length & Found == false)
{
//make path lowercase
filePaths[PathArrayIndex] = filePaths[PathArrayIndex].ToLower();
//if the file is not a system database file
if (filePaths[PathArrayIndex].Contains("app_data") == true)
{
//get the list of files in the folder
dirConts = System.IO.Directory.GetFiles(filePaths[PathArrayIndex], "*.mdf", System.IO.SearchOption.AllDirectories);
Counter = 0;
//while there are files to process
while (Counter < dirConts.Length)
{
//if the file is not a system database file
if (dirConts[Counter].Contains("ASPNETDB.MDF") == false)
{
//add the file to the list of db names
DBNames.Add(dirConts[Counter]);
}
//inc the counter
Counter++;
}
if (DBNames.Count == 1)
{
//flag found
Found = true;
}
else
{
//inc the counter
PathArrayIndex++;
}
}
else
{
//inc the counter
PathArrayIndex++;
}
}
if (Found == false)
{
//move up a path and try again
BaseDir = TrimPath(BaseDir);
}
}
while (BaseDir != "" & Found == false);
//if one database name is found use that
if (DBNames.Count == 1)
{
//return the full path of the db
return DBNames[0];
}
//if no database is founjd throw an exception
else if (DBNames.Count == 0)
{
throw new System.Exception("There is no database in your App_Data folder");
}
//if multiple database have been found throw an error
else
{
throw new System.Exception("You have too many database files in your App_Data folder");
}
}
private string TrimPath(string OldPath)
{
Int32 Posn = 0;
//find the right most instance of \\
Posn = OldPath.LastIndexOf("\\");
if (Posn != -1)
{
//split the path at that point
OldPath = OldPath.Substring(0, Posn);
}
else
{
OldPath = "";
}
return OldPath;
}
public void AddParameter(string ParamName, object ParamValue)
///public method allowing the addition of an sql parameter to the list of parameters
///it accepts two parameters the name of the parameter and its value
{
//create a new instance of the sql parameter object
SqlParameter AParam = new SqlParameter(ParamName, ParamValue);
//add the parameter to the list
SQLParams.Add(AParam);
}
public Int32 Execute(string SProcName)
{
///public method used to execute the named stored procedure
///accepts one parameter which is the name of the stored procedure to use
//open the stored procedure
//initialise the connection to the database
connectionToDB = new SqlConnection(connectionString);
//open the database
connectionToDB.Open();
//initialise the command builder for this connection
SqlCommand dataCommand = new SqlCommand(SProcName, connectionToDB);
//add the parameters to the command builder
//loop through each parameter
for (int Counter = 0; Counter < SQLParams.Count; Counter += 1)
{
//add it to the command builder
dataCommand.Parameters.Add(SQLParams[Counter]);
}
//create an instance of the SqlParameter class
SqlParameter returnValue = new SqlParameter();
//set the direction as the return value
returnValue.Direction = ParameterDirection.ReturnValue;
//add this parameter to the Command builder
dataCommand.Parameters.Add(returnValue);
//set the command type as stored procedure
dataCommand.CommandType = CommandType.StoredProcedure;
//initialise the data adapter
dataChannel = new SqlDataAdapter(SProcName, connectionToDB);
//set the select command property for the data adapter
dataChannel.SelectCommand = dataCommand;
//use the copmmand builder to generate the sql insert delete etc
commandBuilder = new SqlCommandBuilder(dataChannel);
//fill the data adapter
dataChannel.Fill(dataTable);
//close the connection
connectionToDB.Close();
//return the result of the stored procedure
return Convert.ToInt32(returnValue.Value);
}
public Int32 Count
//property that returns the count of records in the query results
{
get
{
//return the count of the query results
return dataTable.Rows.Count;
}
}
public DataTable DataTable
//public property that provides access to the query results
{
get
{
//return the query results
return dataTable;
}
set
{
//set the query results
dataTable = value;
}
}
} |
|
Если нужно будет что то еще дайте пожалуйста знать.
Буду благодарен любой помощи.