Форум программистов, компьютерный форум, киберфорум
C#: Базы данных
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.60/5: Рейтинг темы: голосов - 5, средняя оценка - 4.60
2 / 2 / 1
Регистрация: 28.03.2020
Сообщений: 39

Вывод даных из БД

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;
        }
    }
}
Если нужно будет что то еще дайте пожалуйста знать.
Буду благодарен любой помощи.
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
27.03.2021, 18:14
Ответы с готовыми решениями:

Вывод даных из DataGridView
Доброго времени суток. Есть форма на которой заполняются данные и заносятся в БД Access 2007. Далее в главной форме в DataGridView эти...

Вывод с поля image текстовых даных
привет. В поле image БД ms sql server 05 записаны текстовые файлы как их оттуда вывести в TextBox? хотя бы какие нибуть идеи, работает...

Вывод даных
Помогите с выводом данных, нужно перевести з код консольного режима в обычный, и вывести три результаты в memo. TYPE Tel = integer; ...

1
1497 / 1238 / 245
Регистрация: 04.04.2011
Сообщений: 4,363
27.03.2021, 23:18
Да уж, все "жопные" коды и сам Web Forms выглядят просто смешно
Ах да, извините, к сути.

Хранимка у Вас ясно просит параметр. Где он у Вас передается в Вашем Execute ?

Последний фрагмент - откуда он ? Какое вообще отношение он имеет к Вашему коду, которому нужно просто выбрать датасет (но никак не int32) для показа, вероятно, в гриде ?

Почему Вы не хотите простого, как двери, способа:
C#
1
2
3
SqlCommand cmd = new SqlCommand("EXEC FindBorrower @borsurname", conn);
cmd.Parameters.AddWithValue("@borsurname",borsurname)
        // далее по тексту
И еще. Очень странная хранимка. Зачем она вообще ? Или в "задании" таке указано ?
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
27.03.2021, 23:18
Помогаю со студенческими работами здесь

вывод даных из БД
Доброй ночи ребята. Столкнулся с такой проблемой, не могу вывести данные только одной записи из БД. У меня есть записи в БД с помощью...

Вывод даных
Напишите программу, которая находит все четные натуральные числа не более числа N. Во входном файле input.txt записано одно целое...

Вывод на екран даных
помогите Создать Программу для Формирования списка студентов и преподавателей и выведение его на екран))

Вывод даных из mysql
Есть бд mysql. Из админки сайта добавляется новый товар в таблицу. Товару присваивается автоматически id. При выводе товара на сайт, он...

Stringgrid вывод даных
Всем доброго времени суток Вот нужно написать программу нужно заполнить stringgrid1 составляющими компьютера, фирмами, количеством и...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
SDL3 для Desktop (MinGW): Рисуем цветные прямоугольники с помощью рисовальщика SDL3 на Си и C++
8Observer8 17.03.2026
Содержание блога Финальные проекты на Си и на C++: finish-rectangles-sdl3-c. zip finish-rectangles-sdl3-cpp. zip
Символические и жёсткие ссылки в Linux.
algri14 15.03.2026
Существует два типа ссылок — символические и жёсткие. Ссылка в Linux — это запись в каталоге, которая может указывать либо на inode «файла-ИСТОЧНИКА», тогда это будет «жёсткая ссылка» (hard link),. . .
[Owen Logic] Поддержание уровня воды в резервуаре количеством включённых насосов: моделирование и выбор регулятора
ФедосеевПавел 14.03.2026
Поддержание уровня воды в резервуаре количеством включённых насосов: моделирование и выбор регулятора ВВЕДЕНИЕ Выполняя задание на управление насосной группой заполнения резервуара,. . .
делаю науч статью по влиянию грибов на сукцессию
anaschu 13.03.2026
прикрепляю статью
SDL3 для Desktop (MinGW): Создаём пустое окно с нуля для 2D-графики на SDL3, Си и C++
8Observer8 10.03.2026
Содержание блога Финальные проекты на Си и на C++: hello-sdl3-c. zip hello-sdl3-cpp. zip Результат:
Установка CMake и MinGW 13.1 для сборки С и C++ приложений из консоли и из Qt Creator в EXE
8Observer8 10.03.2026
Содержание блога MinGW - это коллекция инструментов для сборки приложений в EXE. CMake - это система сборки приложений. Здесь описаны базовые шаги для старта программирования с помощью CMake и. . .
Как дизайн сайта влияет на конверсию: 7 решений, которые реально повышают заявки
Neotwalker 08.03.2026
Многие до сих пор воспринимают дизайн сайта как “красивую оболочку”. На практике всё иначе: дизайн напрямую влияет на то, оставит человек заявку или уйдёт через несколько секунд. Даже если у вас. . .
Модульная разработка через nuget packages
DevAlt 07.03.2026
Сложившийся в . Net-среде способ разработки чаще всего предполагает монорепозиторий в котором находятся все исходники. При создании нового решения, мы просто добавляем нужные проекты и имеем. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru