使用Customer[] mAccHolder = new Customer[10];
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
mAccHolder[0] = new Customer("Rich", "Bronze Account", 11);
mAccHolder[1] = new Customer("Patrick", "Silver Account", 21);
mAccHolder[2] = new Customer("Steve", "Gold Account", 12);
mAccHolder[3] = new Customer("Kevin", "Platinum Account", 25);
comboBox1.Items.Add(""); // <- add a blank selection so the user can select NO customer
foreach (Customer r in mAccHolder) {
comboBox1.Items.Add(r.GetName());
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
if (comboBox1.SelectedIndex == -1) {
cstTxtBox.Text = string.Empty;
} else {
if (comboBox1.SelectedItem.ToString() != "") {
Customer selectedCustomer = GetCustomer(comboBox1.SelectedItem.ToString());
if (selectedCustomer != null)
cstTxtBox.Text = selectedCustomer.ToString();
else
cstTxtBox.Text = "Customer not found!";
}
else {
cstTxtBox.Text = "No Customer selected";
}
}
}
private Customer GetCustomer(string targetName) {
foreach (Customer curCustomer in mAccHolder) {
if (curCustomer.Name.Equals(targetName)) {
return curCustomer;
}
}
return null;
}
,我从Oracle数据库中选择数据。
cx_Oracle
有没有办法只返回没有数字索引的名字?例如:
curs = cxn.cursor()
result = curs.execute(SELECT FirstName, LastName FROM Person)
我希望做的是调用for row in result:
result[0] #will return the first column
答案 0 :(得分:3)
除了索引之外,您还可以使用行工厂返回响应名称的行。一种简单的方法是使用collections.namedtuple,如下面的代码(使用cx_Oracle测试套件设置):
from __future__ import print_function # needed for Python 2.7
import cx_Oracle
import collections
connection = cx_Oracle.Connection("cx_Oracle/dev@localhost/orcl")
cursor = connection.cursor()
cursor.execute("select * from TestStrings")
names = [c[0] for c in cursor.description]
cursor.rowfactory = collections.namedtuple("TestStrings", names)
for row in cursor:
print(row)
print(row[0])
print(row.STRINGCOL)
您还可以查看cx_Oracle存储库中提供的示例,以获得更多灵感。
https://github.com/oracle/python-cx_Oracle/blob/master/samples/RowsAsInstance.py
您也可以使用输出类型处理程序使其全部无缝。我稍后会将该示例添加到cx_Oracle存储库中。
答案 1 :(得分:0)
DB API 2.0不提供此类功能。各种DB客户端模块提供的任何内容都是非标准的。
然而,API确实为cursor.description
只读属性提供了以下信息:
此只读属性是7项序列的序列。
这些序列中的每一个都包含描述一个结果的信息 柱:
- 名称
- 类型代码
- display_size
- internal_size
- 精度
- 尺度
- null_ok
前两项(name和type_code)是强制性的,另一项是 五个是可选的,如果没有有意义的值,则设置为None 提供。
&LT; ...&GT;
所以,你可以这样做:
for row in result:
result[(i for i,cd in enumerate(result.description) if cd[0]=='column_name').next()]
相当罗嗦,应该只调用一次,所以将它移到子程序是合理的:
def columns(cursor):
return {cd[0]:i for i,cd in enumerate(cursor.description)}
<...>
result=c.execute(...)
ccls=columns(result)
for row in result:
row[ccls['name']]